How to search a value in Multidimensional Array?

Searching for a specific value within a multidimensional array in PHP can be a common requirement in various web development scenarios. In this comprehensive guide, we'll explore a practical approach to achieve this using PHP functions.

Example


<?php

    $array 
= array(
        array(
            
"id"=>1,
            
"name"=>"test name 1",
            
"email"=>"test1@email.com"
        
),
        array(
            
"id"=>2,
            
"name"=>"test name 2",
            
"email"=>"test2@email.com"
        
),
        array(
            
"id"=>3,
            
"name"=>"test name 3",
            
"email"=>"test3@email.com"
        
),
    );

    
// get all id's in array
    
$array_column array_column($array'id');

    
// search id 2;
    
$key array_search(2$array_column);

    echo 
$array[$key]['name'];

    
// OUTPUT : test name 2;
?>

Understanding the Multidimensional Array

A multidimensional array is an array that contains one or more arrays as its elements. Each internal array can have its own set of key-value pairs, creating a nested or hierarchical structure. In our example, we have an array containing arrays with "id," "name," and "email" as key-value pairs.


<?php

$array 
= array(
    array(
        
"id" => 1,
        
"name" => "test name 1",
        
"email" => "test1@email.com"
    
),
    array(
        
"id" => 2,
        
"name" => "test name 2",
        
"email" => "test2@email.com"
    
),
    array(
        
"id" => 3,
        
"name" => "test name 3",
        
"email" => "test3@email.com"
    
),
);
?>

Extracting Key Values for Search

To efficiently search for a specific value within the multidimensional array, we can use the array_column function. In our example, we extract all "id" values into a separate array.


<?php

// get all id's in array
$array_column array_column($array'id');
?>

Searching for the Value

Now that we have an array containing all


<?php

// search id 2;
$key array_search(2$array_column);
?>

Share