I currently use this code pattern fairly frequently
if(array_key_exists('possible_key', $array)) {
$my_variable = $array['possible_key'];
} else {
$my_variable = 'my default value';
}
Is there a better way to be writing this?
I currently use this code pattern fairly frequently
Is there a better way to be writing this? |
|||
|
One quick change you can do is making use of ternary operator instead of writing if else block.
|
|||||||||||||
|
This is from my library it's similar to the other solutions but it's using a little hack: the array_key_exists() is a slow function so i execute first an isset() 'function' and if it's says "yes, it exists" then i don't have to execute the array_key_exists() function. The reason why isset() is not enough is the isset() will return FALSE if the key exists but the value is NULL. |
|||||||||||||||||
|
I would prefer to keep it simple and not to use if else. Just assign it the default value, and change only when the condition meets.
|
|||
|
Untested code here as I don't have access to my dev machine, but taking Sky's ternary suggestion above and simplifying it (one empty() call is faster than an array_key_exists (see http://stackoverflow.com/questions/6884609/array-key-existskey-array-vs-emptyarraykey)
|
|||||||||||||
|
I prefer to use use isset and make little refactor and wrap that code to function/method
and then use in code
|
|||||||||||||
|