2014-05-06 12 views
7

PHPeoples, sono così stanco di fare questoEsiste un modo idiomatico per ottenere una chiave potenzialmente indefinita da una matrice in PHP?

$value = isset($arr[$key]) ? $arr[$key] : null; 

O questo

$value = array_key_exists($key, $arr) ? $arr[$key] : null; 

Non nessuno mi dicono di fare

$arr = array(1); 
$key = 5; 
$value = $arr[$key]; 
// Notice: Undefined offset: 5 

ho avuto la bronchite. Nessuno ha tempo per farlo.


ho potuto fare una funzione, immagino ...

function array_get(Array $arr, $key, $default=null) { 
    return array_key_exists($key, $arr) 
    ? $arr[$key] 
    : $default 
    ; 
} 

Ma è questo il modo migliore (più idiomatica)?

+0

Questo è ragionevole per me. Io uso lo stesso trucco per ottenere $ _POST o $ _GET params, con un valore predefinito. La tua domanda era migliore prima di aggiungere tutti i trucchetti. – Ibu

+0

Sì, una chiamata di funzione e 2 parametri richiesti sarebbero minimi. – StaticVoid

+0

Chi sottovaluta questo senza un commento? RIP – naomik

risposta

6

modo più elegante di farlo:

function ifsetor(&$value, $default = null) { 
    return isset($value) ? $value : $default; 
} 

Ora si può solo fare:

$value = ifsetor($arr[$key]); 
$message = ifsetor($_POST['message'], 'No message posted'); 

ecc Qui $value viene passato per riferimento, quindi non sarebbe gettare un avviso.

Ulteriori approfondimenti:

1

Se è necessario assicurarsi che esistano alcune chiavi, è possibile creare una matrice predefinita e unire l'input (o qualsiasi altra cosa). In questo modo esisterà tutte le chiavi necessarie e saranno aggiornati, se possibile:

$defaults = array(
    'foo' => '', 
    'bar' => '' 
); 

$data = array_merge($defaults, $someOtherArray); 

Documenti per array_merge(): http://php.net/array_merge

Trovo che questo sia utile se si tiene conto caselle di controllo su un form HTML che può o non apparire in $_GET o $_POST.

Si noti che questo processo prevede chiavi di matrice di stringa, non numeriche. Vedi la documentazione per chiarimenti.

+0

Ho familiarità con questa tecnica, e OK, questo va bene per un array associato che ha i valori predefiniti, ma non ci sono sempre impostazioni predefinite da definire. Questa soluzione non è applicabile per il mio esempio '$ val = $ arr [5]'. – naomik

+0

@naomik Interessante, quando non sapresti quali chiavi ti servono per un pezzo di codice? – Jasper

0

E 'già una funzione built-in se si utilizza $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, è possibile utilizzare:

$value = filter_input(INPUT_GET, $key); 

Inoltre fa molto di più. I filtri opzionali lo rendono utile se vuoi anche convalidare o disinfettare i filtri nello stesso compito.

Returns - Valore della variabile richiesta in caso di successo, FALSE se il filtro non riesce, o NULL se la variabile nome_variabile non è impostata.Se viene utilizzato il flag FILTER_NULL_ON_FAILURE, restituisce FALSE se la variabile è non impostata e NULL se il filtro non riesce.

1

Non dimenticare la funzione isset() non restituisce TRUE per chiavi di matrice che corrispondono ad un valoreNULL, mentre array_key_exists fa(). Quindi la risposta sopra riportata non corregge il lavoro con l'elemento NULL nella matrice. È possibile controllare la mia risposta di modifica per questa situazione. Per esempio abbiamo avuto qualche matrice:

$test = array(NULL,'',0,false,'0'); 

Se usiamo (da risposta di cui sopra in questa discussione) Funzione:

function ifsetor(&$value, $default = null) { 
    return isset($value) ? $value : $default; 
} 

e cercare di ottenere i dati array:

echo '---------------------'; 
var_dump($test); 
echo 'Array count : '.count($test).'<br>'; 
echo '---------------------'; 
var_dump(ifsetor($test[0], 'Key not exists')); 
var_dump(ifsetor($test[1],'Key not exists')); 
var_dump(ifsetor($test[2],'Key not exists')); 
var_dump(ifsetor($test[3], 'Key not exists')); 
var_dump(ifsetor($test[4],'Key not exists')); 
var_dump(ifsetor($test1[5],'Key not exists')); 

function ifsetor(&$value, $default = null) { 
    return isset($value) ? $value : $default; 
} 

nostro risultato be:

--------------------- 

array (size=5) 
    0 => null 
    1 => string '' (length=0) 
    2 => int 0 
    3 => boolean false 
    4 => string '0' (length=1) 

Array count : 5 
--------------------- 

string 'Key not exists' (length=9) //But value in this key of array - NULL! and key exists 

string '' (length=0) 

int 0 

boolean false 

string '0' (length=1) 

string 'Key not exists' (length=9) 

Quindi possiamo ch eck usa isset e array_key_exists insieme. Non dimenticare che questo è array o no;

echo '---------------------'; 
var_dump($test); 
echo 'Array count : '.count($test).'<br>'; 
echo '---------------------'; 
var_dump(array_get($test, 0, 'Key not exists')); 
var_dump(array_get($test, 1,'Key not exists')); 
var_dump(array_get($test, 2,'Key not exists')); 
var_dump(array_get($test, 3, 'Key not exists')); 
var_dump(array_get($test, 4,'Key not exists')); 
var_dump(array_get($test, 5,'Key not exists')); //Key not exists 
var_dump(array_get($test1, 5,'Key not exists')); //This is not array 


function array_get($arr, $key, $default=null) { 
    if(is_array($arr)){ 
    return isset($arr[$key]) || array_key_exists($key, $arr) 
     ? $arr[$key] 
     : $default; 
    }else{ 
    return 'No array given'; 
    } 

} 

Ora la risposta è corretta:

--------------------- 

array (size=5) 
    0 => null 
    1 => string '' (length=0) 
    2 => int 0 
    3 => boolean false 
    4 => string '0' (length=1) 

Array count : 5 
--------------------- 

null //Perfect - key exists! 

string '' (length=0) 

int 0 

boolean false 

string '0' (length=1) 

string 'No array given' (length=14) 

string 'Key not exists' (length=14) 
+0

Perché qualcuno ha downvoted? Spiega per favore. – Brotheryura

+0

Non ho eseguito il downgrade, ma è necessario utilizzare 'return isset ($ value)? ...' invece di 'return $ value? ... ' – naomik

+0

@naomik Perché è necessario utilizzare ** isset ** ? Spiega per favore? Noi usiamo '?' - L'espressione (expr1)? (expr2): (expr3) valuta expr2 se expr1 restituisce TRUE ed espr3 se expr1 restituisce FALSE – Brotheryura

Problemi correlati