1

How do I count number of elements in an array that are not null?

For this array I should get 3:

$array = array();
$array[0] = 'foo';
$array[1] = '';
$array[2] = 'bar'; 
$array[3] = 'blabla'; 

How can I achieve this in PHP?

1
  • null<>empty .correct your question Commented Sep 7, 2011 at 6:08

2 Answers 2

5

Use array_filter [docs]:

count(array_filter($myarray))
Sign up to request clarification or add additional context in comments.

Comments

2
$count = 0;
foreach ($array as $k=>$v) {
    if (!empty($v)) {
        $count++;
    }
}

echo $count; // 3 with your array

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.