0

I have an array that looks something like this:

$array = array(
    array('Field1' => 'red',  'Field2' => 'green',   'Field3' => 'blue'),
    array('Field1' => 'pink', 'Field2' => 'pinkish', 'Field3' => 'barbiecolor'),
    array('Field1' => 'red',  'Field2' => 'blue', '   Field3' => 'orange')
);

And I want to check this by the given values:

$searchBy = array('Field1' => 'red', 'Field2' => 'blue');

What I want to achieve, is to return the parent array that has all associative key & value pairs matched. I've tried in_array() but it doesn't work..

2 Answers 2

3

array_filter may be better for this:

$matches = array_filter($array,function($a) use ($searchBy) {
    foreach($searchBy as $k=>$v) {
        if( $a[$k] != $v) return false;
    }
    return true;
});
Sign up to request clarification or add additional context in comments.

4 Comments

Do note the minimal required PHP version though ;)
Oh yes. This'll work in PHP 5.3, but before that you will need to use create_function instead.
@Kolink - thanks works perfect! In the interest of older versions, how do you define this search function? Thanks
Something like this: create_function('$a','global $searchBy; foreach($searchBy as $k=>$v) {if($a[$k] != $v) return false;} return true;');
1

You can try:

$find = array_filter($array, function ($a) use($searchBy) {
    return array_intersect_assoc($searchBy, $a) == $searchBy;
});

See Live Demo

Old School Version

$find = find($searchBy, $array);
print_r($find);

// Function used
function find($needle, $haystack) {
    $r = array();
    foreach ( $haystack as $k => $a ) {
        array_intersect_assoc($needle, $a) == $needle and $r[$k] = $a;
    }
    return $r;
}

Old School Demo

2 Comments

is it possible to achieve this with PHP < 5.3 ?
@Matt i won't post it because if am not using loop am forced to use globals which i don't believe in 3v4l.org/IRLu5 but i would update with a simple loop version

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.