Voting

: six plus one?
(Example: nine)

The Note You're Voting On

jw at jwscripts dot com
19 years ago
Re-using variables which where references before, without unsetting them first, leads to unexpected behaviour.

The following code:

<?php

$numbers
= array();

for (
$i = 1; $i < 4; $i++) {
$numbers[] = null;
$num = count($numbers);
$index =& $numbers[$num ? $num - 1 : $num];
$index = $i;
}

foreach (
$numbers as $index) {
print
"$index\n";
}

?>

Does not produce:
1
2
3

But instead:
1
2
2

Applying unset($index) before re-using the variable fixes this and the expected list will be produced:
1
2
3

<< Back to user notes page

To Top