2009-12-27 35 views
47

Esempio: Sto controllando l'esistenza di un elemento di matrice come questo:Come verificare se esiste un elemento dell'array?

if (!self::$instances[$instanceKey]) { 
    $instances[$instanceKey] = $theInstance; 
} 

Tuttavia, continuo a ricevere questo errore:

Notice: Undefined index: test in /Applications/MAMP/htdocs/mysite/MyClass.php on line 16 

Naturalmente, la prima volta voglio un'istanza $ istanze non conosceranno la chiave. Immagino che il mio assegno per l'istanza disponibile sia sbagliato?

risposta

86

È possibile utilizzare il costrutto linguaggio isset o la funzione array_key_exists.

isset dovrebbe essere un po 'più veloce (in quanto non è una funzione), ma restituisce false se l'elemento esiste e ha il valore NULL.


Ad esempio, considerando questa matrice:

$a = array(
    123 => 'glop', 
    456 => null, 
); 

E quei tre prove, basandosi su isset:

var_dump(isset($a[123])); 
var_dump(isset($a[456])); 
var_dump(isset($a[789])); 

Il primo ti porterà (esiste l'elemento, ed è non null):

boolean true 

mentre la seconda si arriva (esiste l'elemento, ma è nullo):

boolean false 

E l'ultimo si arriva (l'elemento non esiste):

boolean false 


D'altra parte, utilizzando array_key_exists come questo:

var_dump(array_key_exists(123, $a)); 
var_dump(array_key_exists(456, $a)); 
var_dump(array_key_exists(789, $a)); 

si otterrebbe queste uscite:

boolean true 
boolean true 
boolean false 

Perché, nei due primi casi, l'elemento esiste - anche se è nullo nel secondo caso. E, naturalmente, nel terzo caso, non esiste.


Per situazioni come la tua, io di solito uso isset, considerando non sono mai nel secondo caso ... Ma scegliere quale usare è ora a voi ;-)

Ad esempio, il tuo codice potrebbe diventare qualcosa del genere:

if (!isset(self::$instances[$instanceKey])) { 
    $instances[$instanceKey] = $theInstance; 
} 
+0

Devo lamentarmi perché "isset" non è sicuro. Chiamato '$ form = [1 => 5]; var_dump (isset ($ from [1])); 'restituisce' false' poiché '$ from' non esiste e non viene nemmeno notificato da' E_NOTICE'. Più lento, ma più sicuro 'array_key_exists' fa la cosa per me. – hejdav

4

Si desidera utilizzare la funzione array_key_exists.

6

È possibile utilizzare isset() proprio per questo.

$myArr = array("Name" => "Jonathan"); 
print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ; 
10

È possibile utilizzare la funzione array_key_exists per farlo.

Ad esempio,

$a=array("a"=>"Dog","b"=>"Cat"); 
if (array_key_exists("a",$a)) 
    { 
    echo "Key exists!"; 
    } 
else 
    { 
    echo "Key does not exist!"; 
    } 

PS: Esempio preso da here.

23

array_key_exists() è SLOW rispetto a isset(). Una combinazione di questi due (vedi sotto il codice) sarebbe d'aiuto.

Prende i vantaggi prestazionali isset() mantenendo il risultato di controllo corretto (cioè restituire TRUE anche quando l'elemento di matrice è NULL)

if (isset($a['element']) || array_key_exists('element', $a)) { 
     //the element exists in the array. write your code here. 
} 

Il confronto comparativa: (estratto da sotto post di blog).

array_key_exists() only : 205 ms 
isset() only : 35ms 
isset() || array_key_exists() : 48ms 

Vedi http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/ e http://thinkofdev.com/php-isset-and-multi-dimentional-array/

per la discussione dettagliata.

+0

E, * isset * è anche fuorviante. Perché una parola chiave denominata "è impostata" restituisce * falso * quando viene impostata una variabile o una posizione di matrice, anche se è impostata su * null *? –

+0

La risposta più sofisticata! – Hafenkranich

5

Secondo il manuale php, è possibile farlo in due modi. Dipende da cosa devi controllare.

Se si desidera controllare se il parametro chiave o indice esiste nella matrice utilizzare array_key_exists

<?php 
$search_array = array('first' => 1, 'second' => 4); 
if (array_key_exists('first', $search_array)) { 
echo "The 'first' element is in the array"; 
} 
?> 

Se si vuole verificare se esiste un valore in un array utilizzare in_array

<?php 
$os = array("Mac", "NT", "Irix", "Linux"); 
if (in_array("Irix", $os)) { 
echo "Got Irix"; 
} 
?> 
1

È inoltre possibile utilizzare array_keys per il numero di occorrenze

<?php 
$array=array('1','2','6','6','6','5'); 
$i=count(array_keys($array, 6)); 
if($i>0) 
echo "Element exists in Array"; 
?> 
2

Un piccolo aneddoto per illustrare l'uso di array_key_exists.

// A programmer walked through the parking lot in search of his car 
// When he neared it, he reached for his pocket to grab his array of keys 
$keyChain = array(
    'office-door' => unlockOffice(), 
    'home-key' => unlockSmallApartment(), 
    'wifes-mercedes' => unusedKeyAfterDivorce(), 
    'safety-deposit-box' => uselessKeyForEmptyBox(), 
    'rusto-old-car' => unlockOldBarrel(), 
); 

// He tried and tried but couldn't find the right key for his car 
// And so he wondered if he had the right key with him. 
// To determine this he used array_key_exists 
if (array_key_exists('rusty-old-car', $keyChain)) { 
    print('Its on the chain.'); 
} 
Problemi correlati