9
Array
    (
        [0] => 'hello'
        [1] => 'there'
        [2] => 
        [3] => 
        [4] => 3
    )

// how to  get the number 5?
1
  • I was looking at my own code wrong which made me think that count ignored null values. Commented Nov 5, 2010 at 14:05

6 Answers 6

27

count

$arr = Array
    (
        0 => 'hello',
        1 => 'there',
        2 => null,
        3 => null,
        4 => 3,
    );
var_dump(count($arr));

Output:

int(5)

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

2 Comments

count(array_keys($arr)) then perhaps?
In the sample, even if keys (2,3) are empty, count will still count them as they exists. count($arr) even if there false,null,0,"" etc, aslong as they exists count() will add them up, As MatTheCat says, echo count(array(1,null,null)); gives 3
4

count() or sizeof

2 Comments

that will ignore the values of null ;)
So why echo count(array(1,null,null)); gives me 3??
3

Works for me w/ NULL

$array = array('hello', 'there', NULL, NULL, 3);

echo "<pre>".print_r($array, true)."</pre><br />";
echo "Count: ".count($array)."<br />";

output

Array
(
    [0] => hello
    [1] => there
    [2] => 
    [3] => 
    [4] => 3
)

Count: 5

A quick Google search for PHP Array should pull up results of all the functions available

Comments

1

Below code was tested with PHP 5.3.2. and the output was int 5.

$a = array(
    0 => 'hello',
    1 => 'there',
    2 => null,
    3 => null,
    4 => 3,
);

var_dump(count($a));

Can you please provide more information about null not being counted? An older version maybe? Or simply messing with the rest of us? :)

EDIT: well, posted wrong code :)

Comments

0
echo count($array);

Comments

0

If you want to try something different you can also do it by getting the max array key and adding +1 to account for the first array starting with zero.

$count = max(array_keys($my_array))+1;
echo $count;

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.