1
Array
(
[0] => Array
    (
        [name] => WWW
    )

[1] => Array
    (
        [name] => Hi
    )

[2] => Array
    (
        [name] => Hello
    )

[3] => Array
    (
        [name] => World
    )

)

I have the above array and I want to count the number of keys.

When using the following code

$temp = array_keys($array);
echo $temp;

the result is 2 instead of 4 (0,1,2,3). What I'm doing wrong ?

4
  • 8
    Just count the array itself: count($array). There's always the same amount of keys as there are values! Commented Jan 3, 2014 at 16:35
  • 2
    array_keys returns an array. So how can the result be '2'?? Commented Jan 3, 2014 at 16:36
  • The result of echo $temp; should be 'Array', since array_keys returns an array of the keys. Commented Jan 3, 2014 at 16:37
  • @JosephSilber with the mess of bad answers below, you need to just post yours so we can upvote it =) Commented Jan 3, 2014 at 16:41

3 Answers 3

4

You need to count the array in order to get a number:

  $arr = array
    (
        "0" => array
        (
            "name" =>"WWW"
        ),

    "1" => array
    (
        "name" => "Hi"
    ),

    "2" => array
    (
        "name" => "Hello"
    ),

    "3" => array
    (
        "name" => "World"
    )

    );

    $keys_count = count($arr);
    echo $keys_count;
Sign up to request clarification or add additional context in comments.

Comments

4

Just count the array itself: count($array).

There's always the same amount of keys as there are values!

Comments

-1

Very simple buddy. Look this:

 $array = array(0 => 100, "color" => "red");
 print_r(count($array));

php.net help you for all! ;)

2 Comments

Even simpler echo count($array);. Done.
Using array_keys is unnecessary. So is using print_r on an integer.

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.