1

How do I count non-empty array items in PHP but excluding 0. Zero is a falsy value that's why it's not included in the counting when I use array_filter. In the example below what I want to get when I echo the count is 4 since there are 4 items in the array

$numbers = array(0,2,4,2);
echo count(array_filter($numbers));

And if it is like this the output should be 5, empty string excluded from the counting but the 2 zeroes are still included:

$numbers = array(0,2,4,2,'',0);
echo count(array_filter($numbers));

1 Answer 1

1

Remove unwanted elements from $numbers with array_diff().

echo count(array_diff($numbers, array(0)));  // 3
Sign up to request clarification or add additional context in comments.

Comments

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.