Example: I’m checking for the existence of an array element like this:
if (!self::$instances[$instanceKey]) {
$instances[$instanceKey] = $theInstance;
}
However, I keep getting this error:
Notice: Undefined index: test in /Applications/MAMP/htdocs/mysite/MyClass.php on line 16
Of course, the first time I want an instance, $instances will not know the key. I guess my check for available instance is wrong?
You can use either the language construct
isset, or the functionarray_key_exists.issetshould be a bit faster (as it’s not a function), but will return false if the element exists and has the valueNULL.For example, considering this array :
And those three tests, relying on
isset:The first one will get you (the element exists, and is not null) :
While the second one will get you (the element exists, but is null) :
And the last one will get you (the element doesn’t exist) :
On the other hand, using
array_key_existslike this :You’d get those outputs :
Because, in the two first cases, the element exists — even if it’s null in the second case. And, of course, in the third case, it doesn’t exist.
For situations such as yours, I generally use
isset, considering I’m never in the second case… But choosing which one to use is now up to you 😉For instance, your code could become something like this :