1

i have this array :

$array = array('a' => 'value of a', 'b' => 'value of b', 'c' => 'value of c',
    'd' => 'value of d');

this list of items :

$items = array ('a' => 'value','b'=> 'value','c'=> 'value','d'=> 'value');

i want to check if at least one of the keys of $items exist in $array, if so return an array with one / availableones and its/their values.

this is what i have tried so far, but cant get it right :

if (array_key_exists('a', $array) || array_key_exists('b', $array)
    || array_key_exists('c', $array) || array_key_exists('d', $array)) { 
}

any help would be appreciated.

thanx

1

4 Answers 4

7

What you need is a intersection of the keys between two arrays. There's a nice function called array_intersect_key()

http://php.net/manual/en/function.array-intersect-key.php

$array = array('a' => 'value of a', 'b' => 'value of b', 'c' => 'value of c', 'd' => 'value of d');
$items = array ('a' => 'value','b'=> 'value','c'=> 'value','d'=> 'value');

print_r(array_intersect_key($array, $items));
Sign up to request clarification or add additional context in comments.

1 Comment

this is the way to do it
0

Is this what you're looking for?

function search_keys($needle, $haystack) {
    $matches = array();
    foreach($needle as $key => $value) {
        if(array_key_exists($key, $haystack)) {
            $maches[$key] = $haystack[$key];
        }
    }
    return $matches;
}

$matches = seach_keys($items, $array);

Comments

0

Create a function like this:

function check_keys ($items, $array){
    $return = false;
    foreach (array_keys($items) as $key){
        if (isset($array[$key])){
            $return = true;
            break;
       }
    }
    return $return;
}

Call it like this:

// returns true or false
var_dump (check_keys ($items, $array));

Comments

0

You probably need something like this

$array = array('a' => 'value of a', 'b' => 'value of b', 'c' => 'value of c', 'd' => 'value of d');
$items = array ('a' => 'value','b'=> 'value','c'=> 'value','d'=> 'value');

foreach($items as $key=>$value){
 if (array_key_exists($key,$array)){

  //your code

 }
}

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.