Getting an unexpected result after using count() in a foreach loop

My expected result is that the $container array has ‘1’ and ‘2’ in it. But instead 1, 2, and 3 are put into it. Can someone please explain what is going on here?

$container_fill = range(1, 10);
$container = array();

foreach ($container_fill AS $num)
{
	if (count($container) < 3) {
		$container[] = $num;
	}


}
var_dump($container);

var_dump result:

array (size=3)
  0 => int 1
  1 => int 2
  2 => int 3

expected:

array (size=3)
  0 => int 1
  1 => int 2

Try dumping $container_fill because that is the array being looped.

[laboriously pecked from a mobile]

Here’s the vardump of $container_fill (done at the very end of script):

array (size=10)
  0 => int 1
  1 => int 2
  2 => int 3
  3 => int 4
  4 => int 5
  5 => int 6
  6 => int 7
  7 => int 8
  8 => int 9
  9 => int 10

I tried it before the foreach as well and got the same thing.

Try echoing the count($container) result before the < 3 test.

The values should be 0, 1, 2

I put a var_dump before the line “if (count($container) < 3) {”

Here is each iteration’s result:

array (size=0)
  empty

array (size=1)
  0 => int 1

array (size=2)
  0 => int 1
  1 => int 2

array (size=3) (repeats)
  0 => int 1
  1 => int 2
  2 => int 3

My aim is that after $container reaches 2 elements, no more elements are added to the array. Instead, I am getting a 3rd element.

My aim is that after $container reaches 2 elements, no more elements are added to the array. Instead, I am getting a 3rd element.

Change the if statement to < 2 and there will be two satisfying conditions of 0 and 1

1 Like

I had the wrong comparisons going on for some reason. My mistake. And I was thinking this was some strange result… I even went manually through the loop several times but didn’t catch it. Thanks for your help.

1 Like

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