Detect If Keys Are Present In Array In PHP

Whilst the array_key_exists() function exists, it can't tell if one or more keys exist in the array. The array_keys() and array_intersect() functions can be used together to do this.

<?php

$all = [
  'value1',
  'value2',
  'value3',
];

$inputArray = [
  'value1' => TRUE,
  'value5' => TRUE,
];

print_r(array_intersect(array_keys($inputArray), $all));

if (count(array_intersect(array_keys($inputArray), $all)) > 0) {
  echo 'Key found.';
}
else {
  echo 'Key not found.';
}

This will print "Key found" since "value1" is in the input array.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
4 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.