VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-search-by-multiple-key-value-in-php-array/

⇱ How to search by multiple key => value in PHP array ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to search by multiple key => value in PHP array ?

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:

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:


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.


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 :


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


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

)
Comment