2

In PHP 5.5+, how do I check if the given array of associative arrays contains specific key/value pairs. For example:

$some_array = array(
            array(
                "value"=> 1,
                "k1"=> "austin",
                "k2"=> "texas",
                "k3"=> "us"
            ),
            array(
                "value"=> 15,
                "k1"=> "bali",
                "k2"=> "ubud",
                "k3"=> "indonesia"
            ),
            array(
                "value"=> 26,
                "k1"=> "hyd",
                "k2"=> "telangana",
                "k3"=> "india"
            )
));

How do I return the value associated with k1='bali', k2='ubud' and k3='indonesia'? I can loop through each element to check if that combination exists in the array but is there a simpler way to handle this?

1 Answer 1

1

If you have an target array of keys and values, you can filter the main array to only include child arrays that match all the key/value combinations in your target array using array_diff_assoc.

$target =array(
    "k1"=> "bali",
    "k2"=> "ubud",
    "k3"=> "indonesia"
);

$matches = array_filter($some_array, function($item) use ($target) {
    return !array_diff_assoc($target, $item);
});

Inside the array_filter callback, array_diff_assoc will return all the key/value pairs in $target that are not present in $item, so if they all match, you'll get an empty array. Negating that result with ! will return true for matching arrays and false for non-matching arrays.

$matches will be an array of all the child arrays matching your set of key/value pairs, or an empty array if none match.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.