I see this kind of code quite regularly:
$items = [
'one' => 'John',
'two' => 'Jane',
];
if (in_array('two', array_keys($items))) {
// process
}
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
}
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
}
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)