Rehan K
Rehan K

Reputation: 193

count of the array gives wrong value

I'm new to php and its developing . I declared php array:

<?php

     $chk_group[] =array(
         '1' => 'red',
         '2' => 'thi',
         '3' => 'aaa',
         '4' => 'bbb',
         '5' => 'ccc'      
     );

     var_dump($chk_group);

     //continue for loop
     for ($i = 0 ; $i < count($chk_group); $i++) {
         echo count($chk_group);
     }

 ?>

here i'm getting count = 1 please help me to get count of array.

Upvotes: 2

Views: 289

Answers (4)

Masious
Masious

Reputation: 430

As mentioned in the answers, you need to remove the extra [] sign, so that assignment in front of the = sign, is recognized as the variable. With this syntax, you say that first element of your array, is another array.

Upvotes: 1

semirturgay
semirturgay

Reputation: 4201

You have created a multi dimentional array by your this assigment

$chk_group[] = array(
         '1' => 'red',
         '2' => 'thi',
         '3' => 'aaa',
         '4' => 'bbb',
         '5' => 'ccc' 
     );

can you try without the brackets as :

$chk_group = array(
         '1' => 'red',
         '2' => 'thi',
         '3' => 'aaa',
         '4' => 'bbb',
         '5' => 'ccc' 
      );

Upvotes: 3

esdebon
esdebon

Reputation: 2729

try

count($chk_group[0]);

or

$chk_group =array('1' => 'red',
                           '2' => 'thi',
         '3' => 'aaa',
         '4' => 'bbb',
         '5' => 'ccc' 



     );

 count($chk_group);

Upvotes: 2

Casey Rule
Casey Rule

Reputation: 2085

You need to change $chk_group[] to $chk_group in your first line.

In PHP syntax, $chk_group[] = means push the right had value to an array called $chk_group. Your entire array is being stored to $chk_group[0]

What you need instead is:

 $chk_group[] =array(
     '1' => 'red',
     '2' => 'thi',
     '3' => 'aaa',
     '4' => 'bbb',
     '5' => 'ccc' 
 );

Upvotes: 2

Related Questions