Link to home
Start Free TrialLog in
Avatar of LB1234
LB1234

asked on

PHP While statement that increments and echoes from 0 to 10, but skips the number 5

This is what I came up with but 5 is still printed.  Any ideas?  Thanks.

<?php 


$x = 0;

while ($x < 10) {
	echo $x;
	
	if ($x == 5) {
	continue;	
	}

	$x++;
	
	
}

?>

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

The test for "5" should be before the echo statement.
Avatar of LB1234
LB1234

ASKER

I did that, but then the count starts at 1 rather than 0.
SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dan Craciun
<?php 

$x = 0;

while ($x < 10) {
	if ($x != 5) {
	echo $x;	
	}
	$x++;
}
?>

Open in new window


LE: Ray was faster this time :)

HTH,
Dan
Avatar of LB1234

ASKER

All great solutions, but I'm trying to get this figured out using continue specifically.
Good grief!  Why use code that you've already shown does not work??  I think adding "continue" will only confuse the issue.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of LB1234

ASKER

Thanks Guys :)
Note that with the use of "continue" you can wind up with code that duplicates itself.  For example, note the use of two iterations of $x++ in the most recent code example.  While you certainly can do it this way, it just does not make sense to me to complicate a code example that already works.

But that aside, here are some other ways of thinking about the problem:

<?php // demo/temp_lb1234.php
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28422075.html

$arr = array_merge(range(0,4), range(6,10));
foreach ($arr as $num) echo $num;

echo '<br>' . PHP_EOL;

$arr = range(0,10);
unset($arr[5]);
foreach ($arr as $num) echo $num;

Open in new window

Ray, it's probably homework...
Avatar of LB1234

ASKER

It's not homework, just trying to learn and understand.  In general, I understand that efficiency is important, but in programming there are of course many ways to skin a cat, and I'd like to be familiar with many approaches to the same problem.
If you could choose only one book to learn PHP, I would recommend this one.  A month or two with it will save you a year or two of trial and error, I promise!
http://www.amazon.com/PHP-MySQL-Web-Development-4th/dp/0672329166/

Get the latest version and when a new version is released, throw the old one away (or give it to one of your enemies) and replace it with the new copy.
Avatar of LB1234

ASKER

Haha, thanks Ray, I just ordered it. :)  Arrives in two days with Amazon Prime.