DEV Community

Jimmy Klein
Jimmy Klein

Posted on • Updated on

Check the presence of a key in an array in PHP - The right way

I see this kind of code quite regularly:

$items = [
    'one' => 'John',
    'two' => 'Jane',
];

if (in_array('two', array_keys($items))) {
    // process
}
Enter fullscreen mode Exit fullscreen mode

Although functional, there is a much simpler way to check that a key exists: the array_key_exists() method

$items = [
    'one' => 'John',
    'two' => 'Jane',
];

if (array_key_exists('two', $items)) {
    // process
}
Enter fullscreen mode Exit fullscreen mode

This method will just check the presence of the key, regardless of the associated value.

If we also want to test that the value is not null, we can use the isset() function.

if (isset($items['two'])) {
    // process
}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, and let's stay in touch !

If you liked this article, please share. Join me also on Twitter/X for more PHP tips.

Top comments (0)