using array_search for multi dimensional array
function find_car_with_position($cars, $position) {
foreach($cars as $index => $car) {
if($car['Position'] == $position) return $index;
}
return FALSE;
}
array_search for multidimensional array with two attributes
It's probably simplest just to use a foreach
over the values e.g. this function will return a similar value to array_search
:
function find_user($userdb, $attributes) {
foreach ($userdb as $key => $user) {
if (empty(array_diff($attributes, $user))) return $key;
}
return false;
}
echo find_user($userdb, array('name' => 'Stefanie Mcmohn', 'uid' => 5465));
Output
1
Demo on 3v4l.org
PHP multidimensional array search by value
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
This will work. You should call it like this:
$id = searchForId('100', $userdb);
It is important to know that if you are using ===
operator compared types have to be exactly same, in this example you have to search string
or just use ==
instead ===
.
Based on angoru answer. In later versions of PHP (>= 5.5.0
) you can use one-liner.
$key = array_search('100', array_column($userdb, 'uid'));
Here is documentation: http://php.net/manual/en/function.array-column.php.
How to search a multi-dimensional array by multiple values at once in PHP?
You can build your search query as an array and compare the intersection of each item with it.
$search = ['score' => '50', 'name' => 'Bob'];
foreach($data_info_array as $k => $v) {
if ( $search === array_intersect($v, $search) ) {
echo $k;
break;
}
}
@mickmackusa noticed it is safer to use array_intersect_assoc()
here. He's right because when the multi-dimensional array items are unpredictable, nothing forbids to have items like that:
['miaou' => '50', 'graou' => 'Bob', 'score' => '50', 'name' => 'Bob']
where the searched values are also present but for other keys. In this case array_intersect()
returns all correct values (with their corresponding keys of course) regardless the keys in $search
, and the comparison with the search array will return false
.
But using array_intersect_assoc()
, you ensure that only values for keys in $search
are taken in account.
Conclusion: If you let yourself be lulled into sleep by the seeming monotony of multidimensional array items, you won't be immune to surprise when unexpected variations arise.
PHP array_search for multi dimensional array and return key
If you don't need to key, you could use array_filter
$result = array_filter($data, function($item) use ($search) {
return $item[8] == $search;
})[0];
If you need the key, you could modify it like this
$key = false;
$result = array_filter($data, function($item, $k) use ($search, &$key) {
if ($item[8] == $search) {
$key = $k;
return true;
}
return false;
}, ARRAY_FILTER_USE_BOTH)[0];
To handle cases, where no result is found, you have to skip the [0]
party and test if count($result) != 0
in_array() and multidimensional array
in_array()
does not work on multidimensional arrays. You could write a recursive function to do that for you:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Usage:
$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';
PHP Multi-Dimensional array search (with array_search)
In your case array_column($response, "types")
will return an array of arrays. But to get "global array-key (0 or 1), if you search for whatisearchfor2" use the following approach with array_walk
:
$key = null; // will contain the needed 'global array-key' if a search was successful
$needle = "whatisearchfor2"; // searched word
// assuming that $arr is your initial array
array_walk($arr, function ($v,$k) use(&$key, $needle){
if (in_array($needle, $v['types'])){
$key = $k;
}
});
var_dump($key); // outputs: int(1)
Search multi-dimensional array for specific key/value
$key = array_search(array("departmentID"=>2,"userID"=>"3000002"), $arr1);
How to search an multi-dimensional array with multiple search conditions?
With one simple function it's not possible.
Here's a solution with two:
$search = ['pseudo' => 'test', 'journee' => 10];
$keys = array_keys(
array_filter(
$array,
function ($v) use ($search) { return $v['pseudo'] == $search['pseudo'] && $v['journee'] == $search['journee']; }
)
);
$key = $keys[0];
But if you need to find one key only I advise to use foreach
& break
, because you don't have to iterate over all array of values (what will happen with using array_filter
) and stop immediately when certain data is found:
$key = false;
$search = ['pseudo' => 'test', 'journee' => 10];
foreach ($array as $k => $v) {
if ($v['pseudo'] == $search['pseudo'] && $v['journee'] == $search['journee']) {
$key = $k;
// key found - break the loop
break;
}
}
Related Topics
How to Store Null Values in Datetime Fields in MySQL
Using PHP to Populate a <Select></Select> Dropdown
How to Call a PHP Script/Function on a HTML Button Click
PHP Random Shuffle Array Maintaining Key => Value
What Can Use for Datetime::Diff() for PHP 5.2
How to Sort an Array of Utf-8 Strings in PHP
Object of Class Datetime Could Not Be Converted to String
How to Select Randomly with Doctrine
Best Way to Transfer an Array Between PHP and JavaScript
Parse Xml Namespaces with PHP Simplexml
How to Run Array_Filter Recursively in a PHP Array
Joomla 3.2.1 Password Encryption
Replacing MySQL_* Functions with Pdo and Prepared Statements