views:

95

answers:

3

I tried and tried and tried to get this code to work and kept coming up with zilch. So I decided to try it using "for loops" instead and it worked first try. Could somebody tell me why this code is no good?

<?php
$x = $y = 10;

while ($x < 100) {
    while ($y < 100) {
        $num = $x * $y;
        $numstr = strval($num);
        if ($numstr == strrev($numstr)) {
            $pals[] = $numstr;
        }
        $y++;
    }
    $x++;   
}
?>
+2  A: 

You need to reset y before the y loop begins.

While($x < 100){
 $y=10; //... rest of code
Mike Sherov
+10  A: 

you should reset y=10 inside the first while.

$x = 10;

while ($x < 100) {
    $y = 10;
    while ($y < 100) {
        $num = $x * $y;
        $numstr = strval($num);
        if ($numstr == strrev($numstr)) {
            $pals[] = $numstr;
        }
        $y++;
    }
    $x++;   
}
Marco Mariani
It's as simple as that? I set the y variable in the wrong place?
aliov
well, you set it only once.. anyway, if you are looking for palindromes of x*y, you might want to avoid checking _both_ x*y and y*x, so I would set $y=$x instead of $y=10.
Marco Mariani
A: 

For loops which loop over an integer that is incremented I would prefer the for-loop:

for ($x=0; $x < 100; $x++) {
  for ($y=10; $y<100; $y++) {
    $num = $x * $y;
    $numstr = strval($num);
    if ($numstr == strrev($numstr)) {
      $pals[] = $numstr;
    }
  }  
}

IMHO this is much more readable and it's shorter, too.

jigfox