MyBB Community Forums

Full Version: Alternative to 'else if' statement using a loop?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here is an example of the code I have:

$x = 7; // This number could be any number between 1 and infinity. (It will never be infinity, usually the number will be between 1 & 100).

if ($x === 1) {
	$number = 1;
} else if ($x === 2) {
	$number = 2;
} else if ($x === 3) {
	$number = 3;
} else if ($x === 4) {
	$number = 4;
} else if ($x === 5) {
	$number = 5;
} else if ($x === 6) {
	$number = 6;
} else if ($x === 7) {
	$number = 7;
} else if ($x === 8) {
	$number = 8;
} else if ($x === 9) {
	$number = 9;
} else if ($x === 10) {
	$number = 10;
} else if ($x === 11) {
	$number = 11;
} else if ($x === 12) {
	$number = 12;

//} else if (etc...to infinity, until it finds what $x is equal to)

Is there a loop that I could use, to achieve the same functionality, because it would need to loop from 1 until it finds a number.

It will never loop infinite times, because it will always find a number, I just don't know what that number is.

Which loop could I use?
$x = 7;
$number = 1;
while($x != $number) {
    $number++;
}
Something like this?
But isn't this the same as $number = $x ? Big Grin
Consider using a Do While Loop. Something else you can do is a for loop and test the condition in it. If the condition is true use the keyword break.
(2015-01-22, 08:59 AM)Ad Bakker Wrote: [ -> ]
$x = 7;
$number = 1;
while($x != $number) {
    $number++;
}
Something like this?
But isn't this the same as $number = $x ? Big Grin

Close, but how would I make it show the value of $number after it loops?

Right now it just outputs 123456, and then the loop ends at 7.
That is weird. I ran the following test:

<?php
$x = 7; 
$number = 1;
while($x != $number) {
    $number++;
} 
echo "number = ".(string)$number;
?>

and it displayed "number = 7".
Your code works. Thank you very much.