1

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.

3
  • Use array_search() to search for an empty string. Commented May 5, 2020 at 20:35
  • @Barmar that's to be used for finding at a specific index. What if I dont know where the empty value is? Commented May 5, 2020 at 20:55
  • 1
    What do you mean? array_search returns the index. Commented May 5, 2020 at 21:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your answer, but this if (count(array_filter($a1)) < count($a1)) is not only checking but also filtering right? I dont want to make any changes or filtering in the arrays, I just want to check and notify the user.
array_filter() is not by reference, it just returns the filtered array, so it will not change the array you pass through (unless you assign it back, i.e $a = array_filter($a);).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.