Search code examples
phparraysnull

Get first non-null value from a flat array


If I have an array:

[null, 'a', 'b', 'c']

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?


Solution

  • 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.