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
perché è necessaria una funzione per ottenere il valore utilizzando una chiave dell'array. $ a ['chiave'] cosa c'è di sbagliato in questo – zod
@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. –