I have code that is used very extensively which fetches an array from another method, and sometimes returns the first element of that array. Given that null is an acceptable return value for the function, is it worth the performance overhead of calling isset() on the array index (or checking the array length, etc), or is it better to just return the non-existant index (warnings aside). What are the advantages of calling isset() aside from preventing the warning.
The example below is simplified, the real function doesn’t just get the first element of the array.
Return index which may not exist:
function get_array_element(){
$array = get_array(); // function that returns array
return $array[0]; // return index 0 which may not exist
}
Versus checking if index is set:
function get_array_element(){
$array = get_array(); // function that returns array
return (isset($array[0]))? // check if index 0 isset() else return null
$array[0] :
null;
}
Throwing a notice when accessing an undefined index — in theory — should alert you for typos in key names. In practice, if you’re using
issetfirst, you probably just copied the key name there. Or used a numeric index. Or a constant.On the other hand, in most cases you’re accessing an index withour caring wether it’s set or not — and in this scenario, using
issetis just anoying. A lot of languages lets you just retrieve any index without warnings, Javascript for example: just returning anundefined.So I would advice to ignore the notice. Not all of them, because in some cases there really are helpful, so keep them turned on in development, but silence such array access by using
@. Yes, it is ugly, but does its job:Or in simple cases, maybe other solutions fit?