Pavel K
Pavel K

Reputation: 235

PHP - check if multi array keys exist

How I can check if multi array keys exist?

Example:

$array = array(
    array('first_id' => 2, 'second_id' => 4, 'third_id' => 6),
    array('first_id' => 3, 'second_id' => 5, 'third_id' => 7)
);

And now I want to check if in array exist row with params:

first_id = 3,
second_id = 5,
third_id = 6.

in this example, I should get no results, becase third_id = 6 is not exist (it exist but with first_id = 2 and second_id = 4).

How I can check it in easy way in PHP?

Thanks.

Upvotes: 0

Views: 95

Answers (2)

Arbaz Khan
Arbaz Khan

Reputation: 80

You can use isset, array_search, and array_filter

for only one liner try this..

$array = array(
array('first_id' => 2, 'second_id' => 4, 'third_id' => 6),
array('first_id' => 3, 'second_id' => 5, 'third_id' => 7)
);

$first_id = 2;
$second_id = 4;
$third_id = 6;

//check and get array index if exist
$index = array_keys(array_filter($array, function($item) use ($first_id, 
$second_id, $third_id) { return $item['first_id'] === $first_id &&  
$item['second_id'] === $second_id && $item['third_id'] === $third_id; }));

//print out that array index
print_r($array[$index[0]]);

Upvotes: 0

iainn
iainn

Reputation: 17417

PHP's native array equality check will return true for arrays that have the same keys and values, so you should just be able to use in_array for this - it will take care of the "depth" automatically:

$set = [
    ['first_id' => 2, 'second_id' => 4, 'third_id' => 6],
    ['first_id' => 3, 'second_id' => 5, 'third_id' => 7]
];

$tests = [
    ['first_id' => 3, 'second_id' => 5, 'third_id' => 7],
    ['first_id' => 3, 'second_id' => 5, 'third_id' => 6],
    ['first_id' => 2, 'second_id' => 4, 'third_id' => 6],
    ['first_id' => 2, 'second_id' => 5, 'third_id' => 6],
];

foreach ($tests as $test) {
    var_dump(in_array($test, $set));
}

bool(true)

bool(false)

bool(true)

bool(false)

See https://eval.in/936215

If it's important that the array keys are also in the right order, add the third paramater true to the in_array call. This will use strict equality, rather than loose, and require the arrays to be ordered identically. See the information about equality here: http://php.net/manual/en/language.operators.array.php

Upvotes: 3

Related Questions