Wednesday, 10 October 2012

The problem with while loops in PHP.

As a programmer who is rather fond of the language C, I tend to use a lot of while loops. These are great as in C one or more is true and zero is false, so if you are writing a simple Space Invaders clone, you would logically have a variable of type int called lives, so:
int lives = 3;
and in the game pump, you'd simply have:
void gamePump( void )
     while( lives )
          // Do the game routines
So, when lives is zero, it'll call the routine or function or method you've called gameOver, and logically return to the title screen after that. We can use the same logic with PHP, of course, but let's say this time we want to echo out an array of names. You'd do something like:
$names = array( 'Dave', 'Eric', 'Zach', 'Andrew', 'Lisa', 'Andrea', 'Richard' );
$index = 0;
while( $names[ $index ] ) {
     echo $names[ $index ] . PHP_EOL;
This will return an error, which is why the foreach command is there, so the same code in foreach would be:
$names = array( 'Dave', 'Eric', 'Zach', 'Andrew', 'Lisa', 'Andrea', 'Richard' );
foreach( $names as $name ) {
     echo $name . PHP_EOL;
Okay, so the error is solved. But if you wanted to use a while loop specifically, like in C, you'd have to null-terminate the array. In the top example above, you should:
$names = array( 'Dave', 'Eric', 'Zach', 'Andrew', 'Lisa', 'Andrea', 'Richard', null );
// etc...
This works fine if you don't want to sort the array alphabetically. If you do use the sort command, you'll need to use the foreach method above, as the first entry after a straight sort (key zero) will be null.

No comments:

Post a Comment