0

When i set a global array as this

 $items[$users[$clientID]['room']] = array("seat" => $seat, "item_id" => $q[1], "room" => $users[$clientID]['room']);

it is

  $items[4] = array("seat" => 20, "item_id" => 10, "room" => 4);

but when i do a count it telling the length of $items[4] is 3? It should only count 1 because i only have "1" item.

for ( $i=0;$i<count($items[$users[$clientID]['room']]);$i++):
    //something 
endfor;

print_r($items[$users[$clientID]['room']]);

outputs:

Array
( 
    [seat] => 43
    [item_id] => 46
    [room] => 5 
)
 COUNT 3

What am i doing wrong?

2
  • 1
    What's about count($items)?
    – dan-lee
    Jan 12, 2013 at 11:09
  • If the array containing three items then obviously it'll display count as 3
    – J.K.A.
    Jan 12, 2013 at 11:11

2 Answers 2

2

You have defined $items[$users[$clientID]['room']] as one array: but an array that comprises three items - seat, item_id and room - and it is those individual array items that you are counting.

1

$items[$users[$clientID]['room']] is an array and count() returns no of element in an array, if the value to count is not an array it will return 1. See this link for more information about count function.

Count Function - PHP

5
  • Yes OK, so how can i then count the number of arrays in the array $items[.....] ? Jan 12, 2013 at 11:16
  • You need to run an foreach loop and use is_array function.
    – Ravi
    Jan 12, 2013 at 11:22
  • $itemCount = count($items);
    – Mark Baker
    Jan 12, 2013 at 11:22
  • @MarkBaker It will not return the number of arrays, as it may possible that $items contains some non-array records.
    – Ravi
    Jan 12, 2013 at 11:23
  • 1
    $tmpItems = $items; $itemCount = count(array_filter($tmpItems,'is_array'));
    – Mark Baker
    Jan 12, 2013 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.