Count number of items in a foreach loop

I have some simple code as sample where I am trying to count how many items are in a foreach loop, There are 2 items in the loop but when I echo the $count out it shows 11 instead of 2. I would be grateful if someone could help with this. Many thanks.


$count = 0;
foreach ($boxitem as $items) { 

echo $items . '<br />'; ---> This outputs correct number of items
 echo $count;


Why not use the PHP count(…); function?

I would have renamed the values as $boxitems and $item because there are more than one $boxitems and a single $item for each iteration.

Try this:

// $count = 0;
foreach ($boxitem as $key => $items) 
  // $count++;
  echo $key   .'<br />'; // ---> 0 ..  count($boxitem) -1
  echo $items .'<br />'; // ---> This outputs correct number of items
  echo $boxitem[$key] . '<br />'; // ---> This outputs correct item
 echo '<br>count($boxitem) ==> ' .count($boxitem);

// and this
for ($i=0; $i< count($boxitem); $i++) 
  // $count++;
  echo $i .'<br />'; // ---> 0 ... count($boxitem) -1
  echo $boxitem[$i] .'<br />'; // ---> This outputs correct item

That sounds strange. What is the output of



In your first piece of code, this outputs 0.

In the second, this outputs


Totally confused as to whu this is not working. Many thanks

This is the output of the var_dump which is outside the foreach loop. Many thanks


array (size=1) 0 => string ‘DEMOBOX001’ (length=10)


array (size=1) 0 => string ‘DEMOBOX002’ (length=10)

Based on the debugging output, the posted code isn’t the whole code. It’s being executed inside of some other loop that’s producing two separate single element arrays consisting of the strings.

1 Like

as @mabismad says, your code output indicates you’re running a foreach on something that you think is an array of size 11, but is actually 11 arrays of size 1.

Var_dump the original thing that filled $boxitem.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.