- PHP Search Multidimensional Array By key, value and return key
- PHP Search In Multidimensional Array By key, value
- 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
- Conclusion
- Recommended PHP Tutorials
- Author Admin
- array_search
- Return Values
- Examples
- See Also
- User Contributed Notes 16 notes
PHP Search Multidimensional Array By key, value and return key
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 In Multidimensional Array By key, value
- 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:
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
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.
// 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"] ; // 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"] . "
"; >
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
Author Admin
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.
array_search
Note:
If needle is a string, the comparison is done in a case-sensitive manner.
If the third parameter strict is set to true 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 the haystack , 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.
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
$array = array( 0 => ‘blue’ , 1 => ‘red’ , 2 => ‘green’ , 3 => ‘red’ );
?php
$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
User Contributed Notes 16 notes
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.
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.
$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;
$colors = array_column ( $people , ‘fav_color’ );
$found_key = array_search ( ‘blue’ , $colors );
?>
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:
$code = array( «a» , «b» , «a» , «c» , «a» , «b» , «b» ); // infamous abacabb mortal kombat code 😛
// 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 ]);
>
?>
for searching case insensitive better this:
array_search ( strtolower ( $element ), array_map ( ‘strtolower’ , $array ));
?>
var_dump ( array_search ( ‘needle’ , [ 0 => 0 ])); // int(0) (!)
var_dump ( array_search ( ‘needle’ , [ 0 => 0 ], true )); // bool(false)
var_dump ( array_search ( ‘needle’ , [ 0 => 0 ])); // bool(false)
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;
>
$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’)
)
);
$array_keymap = array_recursive_search_key_map($search_value, $nested_array);
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]];
>
usage example:
——————-
echo array_get_nested_value($array_keymap, $nested_array); // insane