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

PhpArraysSearchMultidimensional ArrayArray Column

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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;
}

Solution 2 - Php

** 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'));

Solution 3 - Php

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!';
}

Solution 4 - Php

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;
}

Solution 5 - Php

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';

Solution 6 - Php

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+

Solution 7 - Php

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'];

Solution 8 - Php

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.

Solution 9 - Php

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

Solution 10 - Php

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;
}

Solution 11 - Php

I don't know if this is better or worse for performance, but here is an alternative:

$keys = array_map(function($element){return $element['id'];}, $my_array);
$flipped_keys = array_flip($keys);
if(isset($flipped_keys[40489]))
{
    // true
}

Solution 12 - Php

different between isset vs array_key_exits https://stackoverflow.com/questions/3210935/whats-the-difference-between-isset-and-array-key-exists/3210982

different between == vs === https://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp

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

Solution 13 - Php

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;
}

Solution 14 - Php

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

Solution 15 - Php

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobView Question on Stackoverflow
Solution 1 - PhpDan GrossmanView Answer on Stackoverflow
Solution 2 - PhpManuel PardoView Answer on Stackoverflow
Solution 3 - PhpJazzerView Answer on Stackoverflow
Solution 4 - PhpFriendly CodeView Answer on Stackoverflow
Solution 5 - PhpsteweView Answer on Stackoverflow
Solution 6 - PhpImran QamerView Answer on Stackoverflow
Solution 7 - PhpamphetamachineView Answer on Stackoverflow
Solution 8 - PhpmarcnycView Answer on Stackoverflow
Solution 9 - PhpAnantView Answer on Stackoverflow
Solution 10 - PhpAli AnsariView Answer on Stackoverflow
Solution 11 - PhpMarcusView Answer on Stackoverflow
Solution 12 - PhpRagu DevanView Answer on Stackoverflow
Solution 13 - PhpFaisalView Answer on Stackoverflow
Solution 14 - Phpnageen nayakView Answer on Stackoverflow
Solution 15 - PhpGuillaume ZeemanView Answer on Stackoverflow