$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)
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
Sì, una chiamata di funzione e 2 parametri richiesti sarebbero minimi. – StaticVoid
Chi sottovaluta questo senza un commento? RIP – naomik