[php] Check if a specific value exists at a specific key in any subarray of a multidimensional array

I need to search a multidimensional array for a specific value in any of the indexed subarrays.

In other words, I need to check a single column of the multidimensional array for a value. If the value exists anywhere in the multidimensional array, I would like to return true otherwise false

$my_array = array(    
    0 =>  array(  
        "name"   => "john",  
        "id"    =>  4  
    ),  
    1   =>  array(  
        "name" =>  "mark",  
        "id" => 152  
    ), 
    2   =>  array(  
        "name" =>  "Eduard",  
        "id" => 152  
    )
);

I would like to know the fastest and most efficient way to check if the array $my_array contains a value with the key "id". For example, if id => 152 anywhere in the multidimensional array, I would like true.

This question is related to php arrays search multidimensional-array array-column

The answer is


TMTOWTDI. Here are several solutions in order of complexity.

(Short primer on complexity follows):O(n) or "big o" means worst case scenario where n means the number of elements in the array, and o(n) or "little o" means best case scenario. Long discrete math story short, you only really have to worry about the worst case scenario, and make sure it's not n ^ 2 or n!. It's more a measure of change in computing time as n increases than it is overall computing time. Wikipedia has a good article about computational aka time complexity.

If experience has taught me anything, it's that spending too much time optimizing your programs' little-o is a distinct waste of time better spent doing something - anything - better.

Solution 0: O(n) / o(1) complexity:

This solution has a best case scenario of 1 comparison - 1 iteration thru the loop, but only provided the matching value is in position 0 of the array. The worst case scenario is it's not in the array, and thus has to iterate over every element of the array.

foreach ($my_array as $sub_array) {
    if (@$sub_array['id'] === 152) {
        return true;
    }
}
return false;

Solution 1: O(n) / o(n) complexity:

This solution must loop thru the entire array no matter where the matching value is, so it's always going to be n iterations thru the array.

return 0 < count(
    array_filter(
        $my_array,
        function ($a) {
            return array_key_exists('id', $a) && $a['id'] == 152;
        }
    )
);

Solution 2: O(n log n) / o(n log n) complexity:

A hash insertion is where the log n comes from; n hash insertions = n * log n. There's a hash lookup at the end which is another log n but it's not included because that's just how discrete math works.

$existence_hash = [];
foreach ($my_array as $sub_array) {
    $existence_hash[$sub_array['id']] = true;
}
return @$existence_hash['152'];

I came upon this post looking to do the same and came up with my own solution I wanted to offer for future visitors of this page (and to see if doing this way presents any problems I had not forseen).

If you want to get a simple true or false output and want to do this with one line of code without a function or a loop you could serialize the array and then use stripos to search for the value:

stripos(serialize($my_array),$needle)

It seems to work for me.


You can use this with only two parameter

function whatever($array, $val) {
    foreach ($array as $item)
        if (isset($item) && in_array($val,$item))
            return 1;
    return 0;
}

** PHP >= 5.5

simply u can use this

$key = array_search(40489, array_column($userdb, 'uid'));

Let's suppose this multi dimensional array:

$userdb=Array
(
(0) => Array
    (
        (uid) => '100',
        (name) => 'Sandra Shush',
        (url) => 'urlof100'
    ),

(1) => Array
    (
        (uid) => '5465',
        (name) => 'Stefanie Mcmohn',
        (pic_square) => 'urlof100'
    ),

(2) => Array
    (
        (uid) => '40489',
        (name) => 'Michael',
        (pic_square) => 'urlof40489'
    )
);

$key = array_search(40489, array_column($userdb, 'uid'));

Here is an updated version of Dan Grossman's answer which will cater for multidimensional arrays (what I was after):

function find_key_value($array, $key, $val)
{
    foreach ($array as $item)
    {
        if (is_array($item) && find_key_value($item, $key, $val)) return true;

        if (isset($item[$key]) && $item[$key] == $val) return true;
    }

    return false;
}

Try with this below code. It should be working fine for any kind of multidimensional array search.

Here you can see LIVE DEMO EXAMPLE

function multi_array_search($search_for, $search_in) {
    foreach ($search_in as $element) {
        if ( ($element === $search_for) ){
            return true;
        }elseif(is_array($element)){
            $result = multi_array_search($search_for, $element);
            if($result == true)
                return true;
        }
    }
    return false;
}

If you have to make a lot of "id" lookups and it should be really fast you should use a second array containing all the "ids" as keys:

$lookup_array=array();

foreach($my_array as $arr){
    $lookup_array[$arr['id']]=1;
}

Now you can check for an existing id very fast, for example:

echo (isset($lookup_array[152]))?'yes':'no';

The simplest way is this:

$my_array = array(    
    0 =>  array(  
        "name"   => "john",  
        "id"    =>  4  
    ),  
    1   =>  array(  
        "name" =>  "mark",  
        "id" => 152  
    ), 
    2   =>  array(  
        "name" =>  "Eduard",  
        "id" => 152  
    )
);

if (array_search(152, array_column($my_array, 'id')) !== FALSE)
  echo 'FOUND!';
else
  echo 'NOT FOUND!';

As in your question, which is actually a simple 2-D array wouldn't it be better? Have a look-

Let say your 2-D array name $my_array and value to find is $id

function idExists($needle='', $haystack=array()){
    //now go through each internal array
    foreach ($haystack as $item) {
        if ($item['id']===$needle) {
            return true;
        }
    }
    return false;
}

and to call it:

idExists($id, $my_array);

As you can see, it actually only check if any internal index with key_name 'id' only, have your $value. Some other answers here might also result true if key_name 'name' also has $value


function checkMultiArrayValue($array) {
        global $test;
        foreach ($array as $key => $item) {

            if(!empty($item) && is_array($item)) {
                checkMultiArrayValue($item);
            }else {
                if($item)
                 $test[$key] = $item;

            }
        }
        return $test;   
    }

 $multiArray = array(    
                0 =>  array(  
                      "country"   => "",  
                      "price"    => 4,  
                      "discount-price" => 0,  
               ),);

$test = checkMultiArrayValue($multiArray);
echo "<pre>"
print_r($test);

Will return array who have index and value


A good solution can be one provided by @Elias Van Ootegan in a comment that is:

$ids = array_column($array, 'id', 'id');
echo isset($ids[40489])?"Exist":"Not Exist";

I tried it and worked for me, thanks buddy.

Edited

Note: It will work in PHP 5.5+


I wrote the following function in order to determine if an multidimensional array partially contains a certain value.

function findKeyValue ($array, $needle, $value, $found = false){
    foreach ($array as $key => $item){
        // Navigate through the array completely.
        if (is_array($item)){
            $found = $this->findKeyValue($item, $needle, $value, $found);
        }

        // If the item is a node, verify if the value of the node contains
        // the given search parameter. E.G.: 'value' <=> 'This contains the value'
        if ( ! empty($key) && $key == $needle && strpos($item, $value) !== false){
            return true;
        }
    }

    return $found;
}

Call the function like this:

$this->findKeyValue($array, $key, $value);

Nothing will be faster than a simple loop. You can mix-and-match some array functions to do it, but they'll just be implemented as a loop too.

function whatever($array, $key, $val) {
    foreach ($array as $item)
        if (isset($item[$key]) && $item[$key] == $val)
            return true;
    return false;
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array? Find a file by name in Visual Studio Code Search all the occurrences of a string in the entire project in Android Studio Java List.contains(Object with field value equal to x) Trigger an action after selection select2 How can I search for a commit message on GitHub? SQL search multiple values in same field Find a string by searching all tables in SQL Server Management Studio 2008 Search File And Find Exact Match And Print Line? Java - Search for files in a directory How to put a delay on AngularJS instant search?

Examples related to multidimensional-array

what does numpy ndarray shape do? len() of a numpy array in python What is the purpose of meshgrid in Python / NumPy? Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray Typescript - multidimensional array initialization How to get every first element in 2 dimensional list How does numpy.newaxis work and when to use it? How to count the occurrence of certain item in an ndarray? Iterate through 2 dimensional array Selecting specific rows and columns from NumPy array

Examples related to array-column

Return single column from a multi-dimensional array Check if a specific value exists at a specific key in any subarray of a multidimensional array