Home > Software engineering >  Proper use of arrays and array_key_exists()
Proper use of arrays and array_key_exists()

Time:12-05

I find myself using array_key_exists() a disturbing amount of times. With a huge number of

if(array_key_exists($key, $array)){
    // do stuff with $array[$key];
}

interspersed with

$value = array_key_exists($key, $array)? $array[$key] : "";

Maybe I've developed poor habits by other languages letting you check whether a key exists in an array just by trying to access it.

But the code I'm writing feels super clunky and verbose when array_key_exists() is required most times I'm trying to access an array of data that's not handwritten by me.

Any tips? Maybe I should think about array differently in php? Or are there any modern methods that can help accessing arrays in a more streamlined fashion?

CodePudding user response:

You can use null coalescing operator ?? in PHP >= 7.0

$array = ['fruit' => 'apple', 'tree' => 'oak'];

echo $array['vegetable'] ?? 'default_value'; 

CodePudding user response:

Without knowing your "super clunky" code, one can't really answer your question. But in general one can say that the frequent query for an array_key is nothing reprehensible.

But maybe you could take the approach of checking the individual keys at the beginning of your script or programme. And the setting of the keys is a condition, otherwise they are set with a default value (for example with the ?? operator). This saves you the query in the code about the existence of the key.

But as I said, you would have to see the code. but maybe it helps a little.

  • Related