-
Loop Puzzler
Hi Folks,
Back again with a new problem. I think it's a simple one, but it escapes me:
There are sixty-four buildings numbered building one through building sixty-four. I want to "visit" each of the buildings one time, selecting the building to be visited in random order, but I do not want to visit building six at all. The code accomplishes that seemingly perfectly, except that after reaching the loop limit, I'm echoing one last time, with the building number blank. Here's the code:
PHP Code:
$buildings = range (1, 64);
$building_index = 1;
shuffle ($buildings);
while ($building_index < 65) {
if ($buildings[$building_index] !== 6 ){
echo "Building " . $buildings[$building_index] . " All hail Caesar!<br />";
}
$building_index ++;
}
Here are the last three lines of what the above code produces:
Building 4 All hail Caesar!
Building 56 All hail Caesar!
Building All hail Caesar!
What am I missing?
A.
-
The $buildings array contains data with values 1 - 64, but has index values 0 - 63. The last index value of 64 doesn't exist. If you had php's error_reporting set to E_ALL and display_errors set to ON, you would be getting a php error about an undefined index value.
After you shuffle() the $buildings array, I would just use a foreach(){} loop on that array to output the result. There's no need for any of the code for the $building_index variable. You could also just unset() the 5th index element before you shuffle the array to remove building #6 from the set of data.
-
Of course! So elementary!
Thank you.
A.