(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP
array_search — Searches the array for a given value and returns the first corresponding key if successful
Description
array_search(mixed $needle
, array $haystack
, bool $strict
= false
): int|string|false
Parameters
-
needle
-
The searched value.
Note:
If
needle
is a string, the comparison is done
in a case-sensitive manner. -
haystack
-
The array.
-
strict
-
If the third parameter
strict
is set totrue
then the array_search() function will search for
identical elements in the
haystack
. This means it will also perform a
strict type comparison of the
needle
in thehaystack
,
and objects must be the same instance.
Return Values
Returns the key for needle
if it is found in the
array, false
otherwise.
If needle
is found in haystack
more than once, the first matching key is returned. To return the keys for
all matching values, use array_keys() with the optional
search_value
parameter instead.
Warning
This function may
return Boolean false
, but may also return a non-Boolean value which
evaluates to false
. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.
Examples
Example #1 array_search() example
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
See Also
- array_keys() — Return all the keys or a subset of the keys of an array
- array_values() — Return all the values of an array
- array_key_exists() — Checks if the given key or index exists in the array
- in_array() — Checks if a value exists in an array
turabgarip at gmail dot com ¶
6 years ago
About searcing in multi-dimentional arrays; two notes on "xfoxawy at gmail dot com";
It perfectly searches through multi-dimentional arrays combined with array_column() (min php 5.5.0) but it may not return the values you'd expect.
<?php array_search($needle, array_column($array, 'key')); ?>
Since array_column() will produce a resulting array; it won't preserve your multi-dimentional array's keys. So if you check against your keys, it will fail.
For example;
<?php
$people = array(
2 => array(
'name' => 'John',
'fav_color' => 'green'
),
5=> array(
'name' => 'Samuel',
'fav_color' => 'blue'
)
);$found_key = array_search('blue', array_column($people, 'fav_color'));
?>
Here, you could expect that the $found_key would be "5" but it's NOT. It will be 1. Since it's the second element of the produced array by the array_column() function.
Secondly, if your array is big, I would recommend you to first assign a new variable so that it wouldn't call array_column() for each element it searches. For a better performance, you could do;
<?php
$colors = array_column($people, 'fav_color');
$found_key = array_search('blue', $colors);
?>
cue at openxbox dot com ¶
19 years ago
If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match. Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null. This nuance cost me a lot of time and sanity, so I hope this helps someone. In case you don't know what I'm talking about, here's an example:
<?php
$code = array("a", "b", "a", "c", "a", "b", "b"); // infamous abacabb mortal kombat code :-P
// this is WRONG
while (($key = array_search("a", $code)) != NULL)
{
// infinite loop, regardless of the unset
unset($code[$key]);
}
// this is _RIGHT_
while (($key = array_search("a", $code)) !== NULL)
{
// loop will terminate
unset($code[$key]);
}
?>
stefano@takys dot it ¶
12 years ago
for searching case insensitive better this:
<?php
array_search(strtolower($element),array_map('strtolower',$array));
?>
RichGC ¶
17 years ago
To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.
Take the following two arrays you wish to search:
<?php
$fruit_array = array("apple", "pear", "orange");
$fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange");
if (
$i = array_search("apple", $fruit_array))
//PROBLEM: the first array returns a key of 0 and IF treats it as FALSEif (is_numeric($i = array_search("apple", $fruit_array)))
//PROBLEM: works on numeric keys of the first array but fails on the secondif ($i = is_numeric(array_search("apple", $fruit_array)))
//PROBLEM: using the above in the wrong order causes $i to always equal 1if ($i = array_search("apple", $fruit_array) !== FALSE)
//PROBLEM: explicit with no extra brackets causes $i to always equal 1if (($i = array_search("apple", $fruit_array)) !== FALSE)
//YES: works on both arrays returning their keys
?>
thinbegin at gmail dot com ¶
5 years ago
Despite PHP's amazing assortment of array functions and juggling maneuvers, I found myself needing a way to get the FULL array key mapping to a specific value. This function does that, and returns an array of the appropriate keys to get to said (first) value occurrence.
function array_recursive_search_key_map($needle, $haystack) {
foreach($haystack as $first_level_key=>$value) {
if ($needle === $value) {
return array($first_level_key);
} elseif (is_array($value)) {
$callback = array_recursive_search_key_map($needle, $value);
if ($callback) {
return array_merge(array($first_level_key), $callback);
}
}
}
return false;
}
usage example:
-------------------
$nested_array = $sample_array = array(
'a' => array(
'one' => array ('aaa' => 'apple', 'bbb' => 'berry', 'ccc' => 'cantalope'),
'two' => array ('ddd' => 'dog', 'eee' => 'elephant', 'fff' => 'fox')
),
'b' => array(
'three' => array ('ggg' => 'glad', 'hhh' => 'happy', 'iii' => 'insane'),
'four' => array ('jjj' => 'jim', 'kkk' => 'kim', 'lll' => 'liam')
),
'c' => array(
'five' => array ('mmm' => 'mow', 'nnn' => 'no', 'ooo' => 'ohh'),
'six' => array ('ppp' => 'pidgeon', 'qqq' => 'quail', 'rrr' => 'rooster')
)
);
$search_value = 'insane';
$array_keymap = array_recursive_search_key_map($search_value, $nested_array);
var_dump($array_keymap);
// Outputs:
// array(3) {
// [0]=>
// string(1) "b"
// [1]=>
// string(5) "three"
// [2]=>
// string(3) "iii"
//}
----------------------------------------------
But again, with the above solution, PHP again falls short on how to dynamically access a specific element's value within the nested array. For that, I wrote a 2nd function to pull the value that was mapped above.
function array_get_nested_value($keymap, $array)
{
$nest_depth = sizeof($keymap);
$value = $array;
for ($i = 0; $i < $nest_depth; $i++) {
$value = $value[$keymap[$i]];
}
return $value;
}
usage example:
-------------------
echo array_get_nested_value($array_keymap, $nested_array); // insane
opencart dot ocfilter at gmail dot com ¶
1 year ago
Be careful!
<?php
var_dump
(array_search('needle', [ 0 => 0 ])); // int(0) (!)var_dump(array_search('needle', [ 0 => 0 ], true)); // bool(false)?>
But, in php 8
<?php
var_dump
(array_search('needle', [ 0 => 0 ])); // bool(false)?>
maciej at speccode dot com ¶
7 years ago
FYI, remember that strict mode is something that might save you hours.
If you're searching for a string and you have a "true" boolean on the way - you will get it as result (first occurrence). Example below:
<?php
$arr
= [
'foo' => 'bar',
'abc' => 'def',
'bool' => true,
'target' => 'xyz'
];var_dump( array_search( 'xyz', $arr ) ); //bool
var_dump( array_search( 'xyz', $arr, true ) ); //target?>
azaozz, gmail ¶
14 years ago
Expanding on the comment by hansen{}cointel.de:
When searching for a string and the array contains 0 (zero), the string is casted to (int) by the type-casting which is always 0 (perhaps the opposite is the proper behaviour, the array value 0 should have been casted to string). That produces unexpected results if strict comparison is not used:
<?php
$a = array(0, "str1", "str2", "str3");
echo "
str1 = ".array_search("str1", $a).",
str2 = ".array_search("str2", $a).",
str3 = ".array_search("str3", $a).",
str1 strict = "
.array_search("str1", $a, true).",
str2 strict = ".array_search("str2", $a, true).",
str3 strict = ".array_search("str3", $a, true);
?>
This will return:
str1 = 0, str2 = 0, str3 = 0, str1 strict = 1, str2 strict = 2, str3 strict = 3
codeslinger at compsalot dot com ¶
13 years ago
one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings. (or even a string that looks like a number)
The problem is that unless you specify "strict" the match is done using == and in that case any string will match a numeric value of zero which is not what you want.
-----
also, php can lookup an index pretty darn fast. for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.
<?php
$normal
[$index] = array('key'=>$key, 'data'=>'foo');
$inverse[$key] = $index;
//very fast lookup, this beats any other kind of search
if (array_key_exists($key, $inverse))
{
$index = $inverse[$key];
return $normal[$index];
}
?>
n-regen ¶
14 years ago
If you only know a part of a value in an array and want to know the complete value, you can use the following function:
<?php
function array_find($needle, $haystack)
{
foreach ($haystack as $item)
{
if (strpos($item, $needle) !== FALSE)
{
return $item;
break;
}
}
}
?>
The function returns the complete first value of $haystack that contains $needle.
andreas dot damm at maxmachine dot de ¶
15 years ago
Combining syntax of array_search() and functionality of array_keys() to get all key=>value associations of an array with the given search-value:
<?php
function array_search_values( $m_needle, $a_haystack, $b_strict = false){
return array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
}
?>
Usage:
<?php
$array1 = array( 'pre'=>'2', 1, 2, 3, '1', '2', '3', 'post'=>2);
print_r( array_search_values( '2', $array1));
print_r( array_search_values( '2', $array1, true));
print_r( array_search_values( 2, $array1, true));
?>
Will return:
array(4) {
["pre"] =>
string(1) "2"
[1] =>
int(2)
[4] =>
string(1) "2"
["post"] =>
int(2)
}
array(2) {
["pre"] =>
string(1) "2"
[4] =>
string(1) "2"
}
array(2) {
[1] =>
int(2)
["post"] =>
int(2)
}
yasien dot dwieb at gmail dot com ¶
3 years ago
Beware when using array_search to a mix of string and integer where prefixes of keys may collide, as in my case I have encountered the following situation:
Assume you have the following array:
<?php
$arr = [
1 => 'index 0',
2 => 'index 1',
3 => 'index 2',
'3anothersuffix' => 'index 3'
];$index1 = array_search('3', array_keys($arr)); // 2
$index2 = array_search('3anothersuffix', array_keys($arr)); //2
?>
$index1 and $index2 will be the same
after using strict type search:
<?php
$index1 = array_search('3', array_keys($arr), true); // false
$index2 = array_search('3anothersuffix', array_keys($arr), true); //3
?>
it will not find $index1 at all while returning a correct value for $index2;
stooshie at gmail dot com ¶
11 years ago
Example of a recursive binary search that returns the index rather than boolean.
<?php
// returns the index of needle in haystack
function binSearch($needle, $haystack)
{
// n is only needed if counting depth of search
global $n;
$n++;
// get the length of passed array
$l = count($haystack);
// if length is 0, problem
if($l <= 0)
{
return -1;
}
// get the mid element
$m = (($l+($l%2))/2);
// if mid >= length (e.g. l=1)
if($m >= $l)
{
$m = $m-1;
}
// get the indexed element to compare to the passed element and branch accordingly
$compare = $haystack[$m];
switch(true)
{
case($compare>$needle):
{
// recurse on the lower half
$new_haystack = array_slice($haystack, 0, $m);
$c = count($new_haystack);
$r = binSearch($needle, $new_haystack);
// return current index - (length of lower half - found index in lower half)
return $m - ($c - $r);
break;
}
case($compare<$needle):
{
// recurse on the upper half
$new_haystack = array_slice($haystack, $m, ($l-$m));
$c = count($new_haystack);
$r = binSearch($needle, $new_haystack);
// return current position + found index in upper half
return $m + $r;
break;
}
case($compare==$needle):
{
// found it, so return index
return $m;
break;
}
}
}
?>
helenadeus at gmail dot com ¶
14 years ago
I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.
<?php
$haystack
= array('a','b','a','b');$needle = 'a';print_r(array_search_all($needle, $haystack));//Output will be
// Array
// (
// [0]=>1
// [1]=>3
// )function array_search_all($needle, $haystack)
{#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystackforeach ($haystack as $k=>$v) {
if(
$haystack[$k]==$needle){$array[] = $k;
}
}
return ($array);
}
?>
nordseebaer at gmx dot de ¶
3 years ago
It's really important to check the return value is not false! I used array_search() to determine the index of an value to unset this value and then realized that $arr[false] === $arr[0] !
<?php
$arr = ['apple', 'banana'];var_dump($arr[0] === 'apple'); // true
var_dump($arr[false] === $arr[0]); // true
var_dump($arr[false] === 'apple'); // trueunset($arr[array_search('banana', $arr)]); //index = 1
var_dump($arr);// result
// array(1) {
// [0]=>
// string(5) "apple"
// }unset($arr[array_search('peach', $arr)]); //not found, result is false
var_dump($arr);// result
// array(0) {
// }
// because $arr[false] === $arr[0]
?>
So always check the return of array_search!
kermes [at] thesevens [dot] net ¶
15 years ago
A variation of previous searches that returns an array of keys that match the given value:
<?php
function array_ksearch($array, $str)
{
$result = array();
for($i = 0; $i < count($array); next($array), $i++)
if(strtolower(current($array)) == strtolower($str))
array_push($result, key($array);
return
$result;
}
?>
Usage would be as follows:
<?php
$testArray = array('one' => 'test1', 'two' => 'test2', 'three' => 'test1', 'four' => 'test2', 'five' => 'test1');
print_r(array_ksearch($testArray, 'test1'));
?>
I know this was already answered, but I used this and extended it a little more in my code so that you didn’t have search by only the uid. I just want to share it for anyone else who may need that functionality.
Here’s my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.
Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.
/**
* @param array multidimensional
* @param string value to search for, ie a specific field name like name_first
* @param string associative key to find it in, ie field_name
*
* @return array keys.
*/
function search_revisions($dataArray, $search_value, $key_to_search) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
$keys[] = $key;
}
}
return $keys;
}
Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.
This second example shows you where a value (‘Taylor’) is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name ‘Taylor’ AND are employed).
/**
* @param array multidimensional
* @param string $search_value The value to search for, ie a specific 'Taylor'
* @param string $key_to_search The associative key to find it in, ie first_name
* @param string $other_matching_key The associative key to find in the matches for employed
* @param string $other_matching_value The value to find in that matching associative key, ie true
*
* @return array keys, ie all the people with the first name 'Taylor' that are employed.
*/
function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
if (isset($other_matching_key) && isset($other_matching_value)) {
if ($cur_value[$other_matching_key] == $other_matching_value) {
$keys[] = $key;
}
} else {
// I must keep in mind that some searches may have multiple
// matches and others would not, so leave it open with no continues.
$keys[] = $key;
}
}
}
return $keys;
}
Use of function
$data = array(
array(
'cust_group' => 6,
'price' => 13.21,
'price_qty' => 5
),
array(
'cust_group' => 8,
'price' => 15.25,
'price_qty' => 4
),
array(
'cust_group' => 8,
'price' => 12.75,
'price_qty' => 10
)
);
$findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
print_r($findKey);
Result
Array ( [0] => 2 )
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
In PHP, multidimensional array search refers to searching a value in a multilevel nested array. There are various techniques to carry out this type of search, such as iterating over nested arrays, recursive approaches and inbuilt array search functions.
Iterative Approach:
Iterating over the array and searching for significant match is the simplest approach one can follow. Check if an element of the given array is itself an array or not and add the element to the search path, else run array search on the nested array.
Example:
<?php
function
searchForId(
$search_value
,
$array
,
$id_path
) {
foreach
(
$array
as
$key1
=>
$val1
) {
$temp_path
=
$id_path
;
array_push
(
$temp_path
,
$key1
);
if
(
is_array
(
$val1
)
and
count
(
$val1
)) {
foreach
(
$val1
as
$key2
=>
$val2
) {
if
(
$val2
==
$search_value
) {
array_push
(
$temp_path
,
$key2
);
return
join(
" --> "
,
$temp_path
);
}
}
}
elseif
(
$val1
==
$search_value
) {
return
join(
" --> "
,
$temp_path
);
}
}
return
null;
}
$gfg_array
=
array
(
array
(
'score'
=>
'100'
,
'name'
=>
'Sam'
,
'subject'
=>
'Data Structures'
),
array
(
'score'
=>
'50'
,
'name'
=>
'Tanya'
,
'subject'
=>
'Advanced Algorithms'
),
array
(
'score'
=>
'75'
,
'name'
=>
'Jack'
,
'subject'
=>
'Distributed Computing'
)
);
$search_path
= searchForId(
'Advanced Algorithms'
,
$gfg_array
,
array
(
'$'
));
print
(
$search_path
);
?>
Output:
$ --> 1 --> subject
Recursive Approach:
In case, when levels of nested arrays increase, it becomes hard to write such programs and debug them. In such cases its better to write a recursive program which can cleanly be written without adding any nested for loops.
Example:
<?php
function
array_search_id(
$search_value
,
$array
,
$id_path
) {
if
(
is_array
(
$array
) &&
count
(
$array
) > 0) {
foreach
(
$array
as
$key
=>
$value
) {
$temp_path
=
$id_path
;
array_push
(
$temp_path
,
$key
);
if
(
is_array
(
$value
) &&
count
(
$value
) > 0) {
$res_path
= array_search_id(
$search_value
,
$value
,
$temp_path
);
if
(
$res_path
!= null) {
return
$res_path
;
}
}
else
if
(
$value
==
$search_value
) {
return
join(
" --> "
,
$temp_path
);
}
}
}
return
null;
}
$gfg_array
=
array
(
"school1"
=>
array
(
"year"
=>
"2017"
,
"data"
=>
array
(
'score'
=>
'100'
,
'name'
=>
'Sam'
,
'subject'
=>
'Data Structures'
)
),
"school2"
=>
array
(
"year"
=>
"2018"
,
"data"
=>
array
(
'score'
=>
'50'
,
'name'
=>
'Tanya'
,
'subject'
=>
'Advanced Algorithms'
)
),
"school3"
=>
array
(
"year"
=>
"2018"
,
"data"
=>
array
(
'score'
=>
'75'
,
'name'
=>
'Jack'
,
'subject'
=>
'Distributed Computing'
)
)
);
$search_path
= array_search_id(
'Jack'
,
$gfg_array
,
array
(
'$'
));
print
(
$search_path
);
?>
Output:
$ --> school3 --> data --> name
Multidimensional array search using array_search() method:
The array_search() is an inbuilt function which searches for a given value related to the given array column/key. This function only returns the key index instead of a search path. The array_column() function returns the values from a single column in the input array.
Example:
<?php
$gfg_array
=
array
(
array
(
'score'
=>
'100'
,
'name'
=>
'Sam'
,
'subject'
=>
'Data Structures'
),
array
(
'score'
=>
'50'
,
'name'
=>
'Tanya'
,
'subject'
=>
'Advanced Algorithms'
),
array
(
'score'
=>
'75'
,
'name'
=>
'Jack'
,
'subject'
=>
'Distributed Computing'
)
);
$id
=
array_search
(
'50'
, array_column(
$gfg_array
,
'score'
));
echo
$id
;
?>
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Last Updated :
17 Dec, 2021
Like Article
Save Article
php search multidimensional array by key and value. Through this tutorial, you will learn how to search in multidimensional array for value and return key. And also learn how to search in multidimensional array for key and return value.
First, let us define what a multidimensional array is. A multidimensional array is an array that contains one or more arrays. Each array within the multidimensional array is referred to as a subarray or dimension. The subarrays can also contain other subarrays, which make up a multidimensional array.
For example, consider the following multidimensional array:
$fruits = array( array('name' => 'apple', 'color' => 'red', 'quantity' => 5), array('name' => 'banana', 'color' => 'yellow', 'quantity' => 3), array('name' => 'orange', 'color' => 'orange', 'quantity' => 7), );
This multidimensional array contains three subarrays, each of which represents a fruit. Each subarray has three key-value pairs, which represent the name, color, and quantity of the fruit.
- PHP Search Multidimensional Array By value and return key
- PHP Search Multidimensional Array By key and return value
- PHP search multidimensional array for multiple values
PHP Search Multidimensional Array By value and return key
Here’s an example code in PHP that demonstrates how to search a multidimensional array by value and return the key:
<?php // Sample multidimensional array $employees = array( array('id' => 1, 'name' => 'John', 'age' => 25), array('id' => 2, 'name' => 'Jane', 'age' => 30), array('id' => 3, 'name' => 'Bob', 'age' => 27), array('id' => 4, 'name' => 'Alice', 'age' => 35) ); // Function to search the array by value and return the key function search_multidimensional_array($array, $key, $value) { foreach ($array as $subarray_key => $subarray) { if (isset($subarray[$key]) && $subarray[$key] == $value) { return $subarray_key; } } return false; } // Search the array for an employee with name 'Bob' $key = search_multidimensional_array($employees, 'name', 'Bob'); // Output the result if ($key !== false) { echo "Employee with name 'Bob' found at key: " . $key; } else { echo "Employee with name 'Bob' not found"; } ?>
In this example, we have a multidimensional array $employees
that contains information about employees. We want to search this array by the name of an employee and return the key of the subarray that contains the employee’s information.
To do this, we define a function search_multidimensional_array()
that takes three arguments: the array to search, the key to search for, and the value to search for. The function loops through each subarray in the array using a foreach
loop and checks if the subarray has a key that matches the search key and a value that matches the search value. If a match is found, the function returns the key of the subarray. If no match is found, the function returns false
.
We then call the search_multidimensional_array()
function with the $employees
array, the key 'name'
, and the value 'Bob'
. The function searches the array for an employee with the name 'Bob'
and returns the key of the subarray that contains the employee’s information.
Finally, we output the result of the search using an if
statement. If the function returns a key that is not false
, we output a message indicating that the employee was found and the key where the employee’s information is stored. Otherwise, we output a message indicating that the employee was not found.
PHP Search Multidimensional Array By key and return value
here’s an example of how to search a multidimensional array in PHP by a specific key and return its value:
Suppose we have an array called $users, which contains multiple arrays representing individual users, and each user array has keys such as “id”, “name”, and “email”. We want to search this array for a specific user by their ID and return their name.
$users = array( array( "id" => 1, "name" => "John Smith", "email" => "[email protected]" ), array( "id" => 2, "name" => "Jane Doe", "email" => "[email protected]" ), array( "id" => 3, "name" => "Bob Johnson", "email" => "[email protected]" ) ); $search_id = 2; // The ID of the user we want to find foreach ($users as $user) { if ($user["id"] == $search_id) { $found_name = $user["name"]; break; } } if (isset($found_name)) { echo "The name of user ID $search_id is $found_name."; } else { echo "User ID $search_id not found."; }
In this example, we first define our $users array with three user sub-arrays. We then set $search_id to 2, the ID of the user we want to find. We then use a foreach loop to iterate over each sub-array in $users. Within the loop, we use an if statement to check if the “id” key of the current sub-array matches $search_id. If it does, we set $found_name to the value of the “name” key in that sub-array and break out of the loop. If no match is found, $found_name will not be set.
Finally, we check if $found_name is set and, if so, we echo out the name of the user we found. If $found_name is not set, we echo out a message saying the user was not found.
PHP search multidimensional array for multiple values
Here is an example of how to search a multidimensional array in PHP for multiple values:
Suppose you have a multidimensional array that contains information about various products, and you want to search for products that have both a certain category and a certain price range. The array might look like this:
$products = array( array("name" => "Product 1", "category" => "books", "price" => 10.99), array("name" => "Product 2", "category" => "books", "price" => 15.99), array("name" => "Product 3", "category" => "electronics", "price" => 29.99), array("name" => "Product 4", "category" => "electronics", "price" => 49.99), array("name" => "Product 5", "category" => "clothing", "price" => 19.99) );
To search this array for products that have both the category “books” and a price between $10 and $20, you can use the array_filter()
function in combination with an anonymous function. The anonymous function will take each element of the array as an argument, and return true
if the element matches the criteria, or false
otherwise.
Here’s the code:
// Define the search criteria $category = "books"; $min_price = 10; $max_price = 20; // Define the search function $search_function = function($product) use ($category, $min_price, $max_price) { return ($product["category"] == $category && $product["price"] >= $min_price && $product["price"] <= $max_price); }; // Perform the search $results = array_filter($products, $search_function); // Output the results foreach ($results as $result) { echo $result["name"] . " is in the category " . $result["category"] . " and costs $" . $result["price"] . "<br>"; }
This code defines the search criteria as variables, and then defines an anonymous function that takes a product as an argument and checks if it matches the criteria. The use
keyword is used to pass the search criteria variables into the anonymous function.
The array_filter()
function is then called with the $products
array and the anonymous function as arguments. This filters the array to only contain elements that match the search criteria.
Finally, the code loops through the filtered results and outputs information about each matching product.
Note that this code will only match products that have a category of “books” and a price between $10 and $20. If you want to search for different criteria, you can simply modify the $category
, $min_price
, and $max_price
variables, and adjust the anonymous function accordingly.
Conclusion
The fastest way to search a multidimensional array. In this tutorial, you have learned how to search in a multidimensional array by key, value, and multiple values.
Recommended PHP Tutorials
- PHP Array: Indexed,Associative, Multidimensional
- To Remove Elements or Values from Array PHP
- PHP remove duplicates from multidimensional array
- Remove Duplicate Elements or Values from Array PHP
- How to Convert String to Array in PHP
- Array Push and POP in PHP | PHP Tutorial
- PHP Array to String Conversion – PHP Implode
My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.
View all posts by Admin
Добрый день! Есть многомерный ассоциативниый массив с данными с разными уровнями вложенности. Примерно вот такой:
Array
(
[0] => Array
(
[name1] => FRUITS
[name2] => 50
[name3] => SHTUKA
[name4] => 90
[name5] => RUR
[name6] => Array
(
[0] => Array
(
[name1] => APPLE
[name2] => 30
[name3] => SHTUKA
[name4] => 80
[name5] => RUR
[name6] => Array
(
[0] => Array
(
[name1] => ANTONOVKA
[name2] => 20
[name3] => SHTUKA
[name4] => 70
[name5] => RUR
[name6] =>
[name7] =>
)
[1] => Array
(
[name1] => ZIMNIE
[name2] => 10
[name3] => SHTUKA
[name4] => 65
[name5] => RUR
[name6] =>
[name7] =>
)
)
[name7] =>
)
[name7] =>
)
Как можно сделать функцию, которая рекурсивно проходила бы по всему массиву, ища конкретное значение, например ANTONOVKA, и найдя его записала бы в $result данные из определенных ключей, получив на выходе примерно следующее:
$result = array(
[0] => ANTONOVKA
[1] => 20
[2] => SHTUKA
[3] => 70
[4] => RUR
)
Как я понимаю на входе должно быть:
function findArray ($ar, $findValue, $executeKeys)
$ar — сам большой массив по которому осуществляется поиск
$findValue — Value который надо найти (в примере ANTONOVKA)
$executeKeys — массив с перечнем ключей $executeKeys = array (‘name1′,’name2′,’name3′,’name4′,’name5’)
Решил сам свой вопрос, может кому будет полезно:
function findArray ($ar, $findValue, $executeKeys){
$result = array();
foreach ($ar as $k => $v) {
if (is_array($ar[$k])) {
$second_result = findArray ($ar[$k], $findValue, $executeKeys);
$result = array_merge($result, $second_result);
continue;
}
if ($v === $findValue) {
foreach ($executeKeys as $val){
$result[] = $ar[$val];
}
}
}
return $result;
}