Mohammad
Mohammad

Reputation: 7418

Is there anyway to count how many keys an array has in Php?

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

// how to  get the number 5?

Upvotes: 9

Views: 48210

Answers (6)

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;

Upvotes: 0

teemitzitrone
teemitzitrone

Reputation: 2260

count

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

Output:

int(5)

Upvotes: 27

Martin Bean
Martin Bean

Reputation: 39389

echo count($array);

Upvotes: 0

David Kuridža
David Kuridža

Reputation: 7207

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 :)

Upvotes: 1

Phill Pafford
Phill Pafford

Reputation: 85308

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

Upvotes: 3

MatTheCat
MatTheCat

Reputation: 18721

count() or sizeof

Upvotes: 4

Related Questions