0
[{id: 1, group: core},{id: 2, group: elite},{id: 3, group: elite},{id: 4, group: elite}]

How to check if an id already exits in the array?

I tried in_array(array('id' => 2), $myarray) but it's not working.

2 Answers 2

1

you must pass all array:

in_array(array('id' => 2, 'group' => 'elite'), $myarray)
Sign up to request clarification or add additional context in comments.

1 Comment

Nice but the other array containing id 2 have different value in group.
0

You can use array_column function to extract one column from array and then search for value, like this:

in_array(2, array_column($myarray, 'id'));

This assume that you convert that JSON to associative array and not array of objects.

WARNING: This function is available only on PHP 5.5 and newer, so you can use this workaround for older versions, where function is not exists (on 5.5+ it will use native fast implementation instead):

if (!function_exists('array_column')) {
  function array_column($array, $column_key) {
    $ret = array();
    foreach ($array as $item)
      $ret[] = $item[$column_key];
    return $ret;
  }
}

1 Comment

Just edited answer and added warning about PHP version, please consider this restriction too, because PHP 5.5 is still not standard in lot of webhosting companies.

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.