DEV Community

Jimmy Klein
Jimmy Klein

Posted on • Edited on

1

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)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay