How to search by multiple key => value in PHP array ? (original) (raw)

Last Updated : 15 Jul, 2024

In a multidimensional array, if there is no unique pair of key => value (more than one pair of key => value) exists then in that case if we search the element by a single key => value pair then it can return more than one item. Therefore we can implement the search with more than one key => value pair to get unique items.

Here we have some common approaches:

Table of Content

**Approach 1: Using the iteration method

For each array inside the array, iterate over the search array and if any search key value doesn't match with the corresponding array key value we discard that array and continue the process for the next array. Let's understand this better with an example: Suppose we want to search student details from a list of the student which contains students of different sections, therefore, in this case, rollNo alone might not give the correct output. So we will need to search the list with two key => value that is rollNO and section.

**Example:

php `

value pairs in array function search($array, $search_list) { // Create the result array $result = []; // Iterate over each array element foreach ($array as key=>key => key=>value) { // Iterate over each search condition foreach ($search_list as k=>k => k=>v) { // If the array element does not meet // the search condition then continue // to the next element if (!isset($value[$k]) || value[value[value[k] != $v) { // Skip two loops continue 2; } } // Append array element's key to the //result array result[]=result[] = result[]=value; } // Return result return $result; } // Multidimensional array for students list $arr = [ 1 => [ "rollNo" => 44, "name" => "Alice", "section" => "B", ], 2 => [ "rollNo" => 3, "name" => "Amit", "section" => "B", ], 3 => [ "rollNo" => 3, "name" => "Bob", "section" => "A", ], 4 => [ "rollNo" => 5, "name" => "Gaurav", "section" => "B", ], 5 => [ "rollNo" => 5, "name" => "Gaurav", "section" => "A", ], ]; // Define search list with multiple key=>value pair $search_items = ["rollNo" => 5, "section" => "A"]; // Call search and pass the array and // the search list res=search(res = search(res=search(arr, $search_items); // Print search result foreach ($res as $var) { echo "RollNo: " . $var["rollNo"] . "
"; echo "Name: " . $var["name"] . "
"; echo "Section: " . $var["section"] . "
"; } ?>

`

Output

RollNo: 5Name: GauravSection: A

Approach 2: Using array_filter() and array_intersect_assoc()

To search for elements in a PHP array based on multiple key-value pairs without using foreach, utilize array_filter() with a callback that checks matches using array_intersect_assoc(). This approach efficiently filters array elements based on specified criteria.

**Example: In this example we use array_filter with array_intersect_assoc to filter a list of people based on multiple key-value pairs (age and city), returning matching results efficiently.

PHP `

'John', 'age' => 30, 'city' => 'New York'], ['name' => 'Jane', 'age' => 25, 'city' => 'Los Angeles'], ['name' => 'Doe', 'age' => 35, 'city' => 'Chicago'], ['name' => 'Alice', 'age' => 28, 'city' => 'New York'], ]; // Search criteria (multiple key-value pairs) $criteria = ['age' => 30, 'city' => 'New York']; // Use array_filter to apply the filter results=arrayfilter(results = array_filter(results=arrayfilter(people, function ($person) use ($criteria) { return count(array_intersect_assoc($criteria, person))==count(person)) == count(person))==count(criteria); }); // Print the results print_r($results); ` **Output** Array ( [0] => Array ( [name] => John [age] => 30 [city] => New York ) ) ## Approach 3: Using array\_udiff() The array\_udiff() function can be used to search for elements in a multidimensional array by comparing multiple key-value pairs. This approach allows for custom comparison functions, making it versatile for complex matching criteria. ****Example :** PHP ` 1, 'section' => 'A', 'name' => 'John'], ['rollNo' => 1, 'section' => 'B', 'name' => 'Jane'], ['rollNo' => 2, 'section' => 'A', 'name' => 'Alice'] ]; $searchCriteria = ['rollNo' => 1, 'section' => 'A']; function compare($a, $b) { foreach ($a as key=>key => key=>value) { if (!isset($b[$key]) || b[b[b[key] !== $value) { return value<=>value <=> value<=>b[$key]; } } return 0; } result=arrayudiff(result = array_udiff(result=arrayudiff(students, [$searchCriteria], 'compare'); print_r($result); ?>

`

Output

Array ( [0] => Array ( [rollNo] => 1 [section] => A [name] => John )

[1] => Array
    (
        [rollNo] => 1
        [section]...

Using a foreach Loop

Using a foreach loop in PHP allows iterating through an array to inspect each element. It's commonly used to iterate over associative or indexed arrays, checking conditions or performing operations on each element based on specified criteria.

**Example

PHP `

1, "name" => "John", "age" => 30), array("id" => 2, "name" => "Jane", "age" => 25), array("id" => 3, "name" => "Doe", "age" => 35) ); $searchCriteria = array("id" => 2, "age" => 25); $results = array(); foreach ($array as $item) { $match = true; foreach ($searchCriteria as key=>key => key=>value) { if ($item[$key] !== $value) { $match = false; break; } } if ($match) { results[]=results[] = results[]=item; } } print_r($results); ?>

`

Output

Array ( [0] => Array ( [id] => 2 [name] => Jane [age] => 25 )

)