1

I have three arrays:

$arr_1 = array('a'=>1,'b'=>2);  
$arr_11 = array('a'=>1, 'd'=>4);  
$arr_2 = array('a'=>'aaa','b'=>'bbb', 'c'=>'ccc');  

I want to check that all keys from $arr_1 exist in $arr_2.

someFunction($arr_1,$arr_2); //return true  
someFunction($arr_11,$arr_2); //return false 

I know how to do it with a "foreach" loop.
Is there a better way?

1
  • php.net/array_key_diff - Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values. Commented Nov 27, 2012 at 18:05

4 Answers 4

5

maybe

<?php

array_diff(array_keys($arr_1), array_keys($arr_11));

?>

shorter yes, faster dunno :)

Update from @deceze

<?php 

array_diff_key($arr_1, $arr_11);

?>
Sign up to request clarification or add additional context in comments.

5 Comments

I never used before so i didn't know that func exists. Thx I add it.
from this I get 'c','d'. I won't know form which array the are from
Sorry, but isn't this just going to return all of the keys that are unique to one or the other array? If so, how does he know which array had the "extra" key?
@lvil You want to check whether one array contains keys not in the other. So if the diff operation contains anything, it means that one arrays contained more keys. Read the manual for what exactly the return value means.
@BrianWarshaw array_key_diff is not symmetric. It only returns keys from the first argument that aren't present in any of the others, but not the other way around.
0

You could use array_key_exists() or isset() in a while loop:

$found_missing_key = false
$keys = array_keys($array1);
foreach($keys as $key) {
    if(!isset($array2[$key])) {
        $found_missing_key = true;
        break;
    }
}

Comments

0

Write someFunction yourself, and use a loop inside. A loop and array_key_exists is the way to do this, but you can save yourself having to do it again in the future if you wrap it in a function.

UPDATE

function arrayKeyCompare($control, $variable) {
    foreach (array_keys($control) as $key) {
        if (!array_key_exists($key, $variable)) return false;
    }

    return true;
}

Comments

0

Here is an alternative approach to check if all keys in $arr1 are present in $arr2:

function check($v){
    return array_key_exists($v,$arr_2);
}
count(array_filter(array_keys($arr_1),"check")) == count($arr_1); // true

Note that while you might not have write the loop out yourself, inevitably any sort of search for keys in an array is going to involve one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.