0

In an array like this:

$array = array(
    'value1'=>'',
    'value2'=>'',
    'value3'=>'',
);

We can:

echo count($array);
// Outputs 3

But if we have an array like:

$array = array(
    'value1'=>'',
    'value2'=>'some value',
    'value3'=>'',
);

What is the best way to do the following?

echo someFunction($array);
// Outputs 1
1
  • What result do you expect for [0, 'foo', '', null, false]? Commented Nov 30, 2014 at 11:07

2 Answers 2

4

Use array_filter in order to remove the empty values:

$array = array(
    'value1'=>'',
    'value2'=>'some value',
    'value3'=>'',
);
echo count(array_filter($array)); // prints 1
Sign up to request clarification or add additional context in comments.

Comments

1

loop over the array and test each element for truthy

Same as array_filter, but faster (and does not allocate another array, so less memory used)

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.