fvcxvcxv
fvcxvcxv

Reputation: 85

Check if associative array contains key-value pair

Suppose I have an array whose elements are like this:

$elements = array(
  "Canada" => "Ottawa",
  "France" => "Paris",
  ...
);

How can I check if "Canada" => "Ottawa" is present in this array?

Upvotes: 2

Views: 9301

Answers (3)

agm1984
agm1984

Reputation: 17188

I put a couple of these answers together and arrived at this:

// enum dictionary
$QUERYABLE_FIELDS = [
    'accounts' => [ 'phone', 'business_email' ],
    'users' => [ 'email' ],
];

// search terms
$table = 'users';
$column = 'email';
$value = '[email protected]';

if (array_key_exists($table, $QUERYABLE_FIELDS)) {
    if (in_array($column, $QUERYABLE_FIELDS[$table])) {
        // if table and column are allowed, return Boolean if value already exists
        // this is Laravel PHP, but just note that $exists will either be
        // the first matching record, or null
        $exists = DB::table($table)->where($column, $value)->first();

        if ($exists) return response()->json([ 'in_use' => true ], 200);
        return response()->json([ 'in_use' => false ], 200);
    }

    return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}

return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);

To break it down further, if you have an associative array that has some complex values in it, you can use array_key_exists() to check for them by name.

If the key exists, you can read its value as normal, as shown in my example above, as $QUERYABLE_FIELDS[$table] which will return [ 'email' ], so you could do:

$QUERYABLE_FIELDS['users'][0];

or

in_array('email', $QUERYABLE_FIELDS['users']);

Upvotes: 0

Mark Amery
Mark Amery

Reputation: 155206

Looking down the list of Array Functions in the docs, I don't see anything built-in to do this. But it's easy to roll your own utility function for it:

/*
    Returns true if the $key exists in the haystack and its value is $value.

    Otherwise, returns false.
*/
function key_value_pair_exists(array $haystack, $key, $value) {
    return array_key_exists($key, $haystack) &&
           $haystack[$key] == $value;
}

Example usage:

$countries_to_capitals = [
    'Switzerland' => 'Bern',
    'Nepal' => 'Kathmandu',
    'Canada' => 'Ottawa',
    'Australia' => 'Canberra',
    'Egypt' => 'Cairo',
    'Mexico' => 'Mexico City'
];
var_dump(
    key_value_pair_exists($countries_to_capitals, 'Canada', 'Ottawa')
); // true
var_dump(
    key_value_pair_exists($countries_to_capitals, 'Switzerland', 'Geneva')
); // false

Upvotes: 8

B.J.
B.J.

Reputation: 123

if (isset($elements[$country]) AND $elements[$country] == $capitale) {
    return true;
}
return false;

Upvotes: 3

Related Questions