Open In App

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

Last Updated : 30 May, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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 items. Therefore we can implement the search with more than one key => value pair to get unique items.

Approach: For each array inside the array, iterate over the search array and if any search key value doesn’t match with corresponding array key value we discard that array and continue the process for 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 student of different section, 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
  
// PHP program to search for multiple
// key=>value pairs in array
  
function search($array, $search_list) {
  
    // Create the result array
    $result = array();
  
    // Iterate over each array element
    foreach ($array as $key => $value) {
  
        // Iterate over each search condition
        foreach ($search_list as $k => $v) {
      
            // If the array element does not meet
            // the search condition then continue
            // to the next element
            if (!isset($value[$k]) || $value[$k] != $v)
            {
                  
                // Skip two loops
                continue 2;
            }
        }
      
        // Append array element's key to the
        //result array
        $result[] = $value;
    }
  
    // Return result 
    return $result;
}
  
// Multidimensional array for students list
$arr = array(
    1 => array(
        'rollNo' => 44,
        'name' => 'Alice',
        'section' => 'B'
    ),
    2 => array(
        'rollNo' => 3,
        'name' => 'Amit',
        'section' => 'B'
    ),
    3 => array(
        'rollNo' => 3,
        'name' => 'Bob',
        'section' => 'A'
    ),
    4 => array(
        'rollNo' => 5,
        'name' => 'Gaurav',
        'section' => 'B'
    ),
    5 => array(
        'rollNo' => 5,
        'name' => 'Gaurav',
        'section' => 'A'
    
);
  
// Define search list with multiple key=>value pair
$search_items = array('rollNo'=>5, 'section'=>"A");
  
// Call search and pass the array and
// the search list
$res = search($arr, $search_items);
  
// Print search result
foreach ($res as $var) {
    echo 'RollNo: ' . $var['rollNo'] . '<br>';
    echo 'Name: ' . $var['name'] . '<br>';
    echo 'Section: ' . $var['section'] . '<br>';        
}
  
?>


Output:

RollNo: 5
Name: Gaurav
Section: A


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads