Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get first non-null value from array php

Tags:

arrays

php

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?

like image 795
Drew Bartlett Avatar asked Jun 22 '12 15:06

Drew Bartlett


4 Answers

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.

like image 68
mario Avatar answered Nov 14 '22 00:11

mario


function get_first_not_null($array){
  foreach($array as $v){
    if($v !== null){
        return $v;
    }
  }
  return null;
}
like image 42
Mariusz Jamro Avatar answered Nov 14 '22 01:11

Mariusz Jamro


function getFirstNotNull($array) {
    foreach($array as $val) {
         if(!is_null($val) || !$val) return $val;
    }
}
like image 3
Ruben Nagoga Avatar answered Nov 13 '22 23:11

Ruben Nagoga


$res = null;
foreach ($arr as $v) {
    if ($v !== null) {
        $res = $v;
        break;
    }
}
like image 3
goat Avatar answered Nov 14 '22 01:11

goat