0

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.

2
  • have a look at array_key_exists() or isset() Commented Jan 17, 2018 at 9:30
  • what do you think about LINQ? you can query your arrays like SQL tables. Commented Jan 17, 2018 at 9:32

2 Answers 2

3

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

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

Comments

0

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]]);

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.