2012-03-21 9 views
14

In Python posso usare il metodo "get" per ottenere il valore da un dizionario senza errori.PHP: ottieni il valore dell'array come in Python?

a = {1: "a", 2: "b"} 
a[3] # error 
a.get(3, "") # I got empty string. 

Così ho cercare una funzione comune/base che fanno questo:

function GetItem($Arr, $Key, $Default){ 
    $res = ''; 
    if (array_key_exists($Key, $Arr)) { 
     $res = $Arr[$Key]; 
    } else { 
     $res = $Default; 
    } 
    return $res; 
} 

avere stessa funzione fondamentalmente in PHP come in Python?

Grazie: dd

+1

perché è necessaria una funzione per ottenere il valore utilizzando una chiave dell'array. $ a ['chiave'] cosa c'è di sbagliato in questo – zod

+1

@zod: se la chiave non esiste, si ottiene un errore PHP. L'utilizzo di una funzione come quelle nelle risposte sottostanti consente di ottenere un valore predefinito anziché un messaggio di errore. –

risposta

10

isset() è in genere più veloce di array_key_exists(). Il parametro $default viene inizializzato su una stringa vuota se omesso.

function getItem($array, $key, $default = "") { 
    return isset($array[$key]) ? $array[$key] : $default; 
} 

// Call as 
$array = array("abc" => 123, "def" => 455); 
echo getItem($array, "xyz", "not here"); 
// "not here" 

Tuttavia, se un array key esiste, ma ha un valore NULL, isset() volontà non si comportano come ci si aspetta, in quanto tratterà il NULL come se non esiste e tornare $default. Se ci si aspetta NULL s nella matrice, è necessario utilizzare array_key_exists() invece.

function getItem($array, $key, $default = "") { 
    return array_key_exists($key, $array) ? $array[$key] : $default; 
} 
+2

Ho creato un'altra funzione di supporto che è più semplice e richiede meno argomenti: http://stackoverflow.com/a/25205195/1890285 – stepmuel

0

Non esiste una funzione di base di farlo nella mia mente.

tuo GetItem è un buon modo per fare quello che vuoi fare :)

2
Non

abbastanza. Questo dovrebbe comportarsi allo stesso modo.

function GetItem($Arr, $Key, $Default = ''){ 
    if (array_key_exists($Key, $Arr)) { 
     $res = $Arr[$Key]; 
    } else { 
     $res = $Default; 
    } 
    return $res; 
} 

La prima riga nella funzione è inutile, come ogni percorso di codice risultati in $res essere sovrascritti. Il trucco è rendere il parametro $Default opzionale come sopra.

Ricordare che l'utilizzo di array_key_exists() può causare rallentamenti significativi, soprattutto su array di grandi dimensioni. Un'alternativa:

function GetItem($Arr, $Key, $Default = '') { 
    return isset($Arr[$Key]) ? $Arr[$Key] : $Default; 
} 
0

Sì. oppure

function GetItem($Arr, $Key, $Default) { 
    return array_key_exists($Key, $Arr) 
     ? $Arr[$Key] 
     : $Default; 
} 
Problemi correlati