Sen dil yapısı isset
, or the function array_key_exists
a> kullanabilirsiniz.
isset
biraz daha hızlı (as it's not a function) olmalı, ancak öğe varsa ve değeri varsa return false NULL
.
For example, considering this array :
$a = array(
123 => 'glop',
456 => null,
);
Ve güvenerek bu üç test, isset
:
var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));
İlki alacak (the element exists, and is not null):
boolean true
Ikinci bir alacak olsa (the element exists, but is null):
boolean false
Ve sonuncusu almak (the element doesn't exist) olacak:
boolean false
On the other hand, using array_key_exists
like this :
var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));
O çıkışları almak istiyorum:
boolean true
boolean true
boolean false
İlk iki durumda, unsur vardır, çünkü - bu ikinci durumda boş bile olsa. Ve, elbette, üçüncü durumda, o yok.
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 ;-)
Örneğin, kod böyle bir şey haline gelebilir:
if (!isset(self::$instances[$instanceKey])) {
$instances[$instanceKey] = $theInstance;
}