Search code examples
phparraysarray-filter

How to check if an array has an empty value at an unspecified index in PHP?


How can I check if any of the arrays contains empty fields (they are both dynamic arrays so the empty value can be in any index in both of them)?

Array1 ( [0] => dfsg [1] => dfasg [2] => d5g [3] => )
Array2 ( [0] => d54fgv [1] => [2] => df4g4 [3] => d645 )

It would be good to know at which index as well, otherwise, just to know if there is any empty fields.


Solution

  • There are many ways to achieve this. One that springs to mind is checking if the count of a filtered version is lesser than the original array. You can even customize this to specify which sort of filter-values you are looking for by supplying a closure to array_filter().

    if (count(array_filter($a1)) < count($a1)) {
        echo '$a1 has at least one empty value';
    }
    

    From the manual of array_filter(),

    If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.

    If you need to know which index(es) is empty, you can check the difference of the filtered array with the original array through array_diff(). You can then use array_keys() on the filtered array to obtain all the indexes.