1

I tend to find that when using foreach stuctures without using references, some elements of the array are missing.

$array = array();

/* ... */

$array[] = 1;
$array[] = 2;
$array[] = 3;

/* ... */

print_r($array); /* print_r always shows all elements */

foreach ($array as $element) { /* missing elements */ }
foreach ($array as &$element) { /* does a fine job */ }

I have had three independent occurrences of this in my code. The fix is easy (add &), but it sounds like a bug either in PHP or in my setup...

Are more people experiencing this? What is the problem?

PHP 5.4.12


EDIT

Case:

$a = array();
$a[] = 1;
$a[] = 2;
$a[] = 3;

foreach ($a as &$e)
{
    echo $e;
}

echo '<br>';

foreach ($a as $e)
{
    echo $e;
}

Output:

123
122
Taco de Wolff
  • 1,682
  • 3
  • 17
  • 34

2 Answers2

0

Just confirmed.

<?php
  $x[]=1;
  $x[]=2;
  $x[]=3;
  $x[]=4;
  foreach($x as $y) {
    var_dump($y);
  }
?>

int(1) int(2) int(3) int(4)

nickb
  • 59,313
  • 13
  • 108
  • 143
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
0

It seems that this issue is solved in PHP ver. 5.6.10.

I have an array with 8 elements. Here is the var_dump:

array(8) { [0]=> string(18) "lname is required." [1]=> string(18) "fname is required." [2]=> string(18) "email is required." [3]=> string(22) "password1 is required." [4]=> string(22) "password2 is required." [5]=> string(44) "First Name must be letters and numbers only." [6]=> string(43) "Last Name must be letters and numbers only." [7]=> string(22) "Invalid e-mail address" }

I print out the array using this code:

foreach ($_SESSION['error'] as $error) { print $error . "
\n"; }

My MAMP localhost uses PHP ver. 5.6.10 and the result is perfect:

"lname is required. fname is required. email is required. password1 is required. password2 is required. First Name must be letters and numbers only. Last Name must be letters and numbers only. Invalid e-mail address"

My remote server uses PHP ver. 5.3 and in this case the server prints only the first element:

"lname is required."

When I changed the code as Taco suggested (foreach ($_SESSION['error'] as &$error)) the ver. 5.3. also gave the good (and expected) result.

Skipper
  • 11
  • 2