If I have an array:
Array
(
[0] =>
[1] => a
[2] => b
[3] => c
)
And I want to get the first non-null value from the array, in this case "a". How could I go about doing that nice and easily?
Not sure about nice and easy. But a short approach might be:
$first = current(array_filter($sparse_array));
Where array_filter
will extract you the "truthy" values, thus skipping empty and false entries. While current
simply gives you the first of those remaining entries.
function get_first_not_null($array){
foreach($array as $v){
if($v !== null){
return $v;
}
}
return null;
}
function getFirstNotNull($array) {
foreach($array as $val) {
if(!is_null($val) || !$val) return $val;
}
}
$res = null;
foreach ($arr as $v) {
if ($v !== null) {
$res = $v;
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With