Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's a few things going on here... </p> <p>First, I'm not sure if you're aware that <code>unset</code>'ing the array doesn't actually remove the indices: </p> <pre><code>$array = array(0, 1, 2, 3); unset($array[2]); var_dump($array); /* array(3) { [0]=&gt; int(0) [1]=&gt; int(1) [3]=&gt; int(3) } */ </code></pre> <p>So you're going to have some undefined offsets when you iterate over the elements in the array. To go one by one, you should use the <code>foreach</code> loop control. </p> <p>Another issue lies in the nested for loop here: </p> <pre><code>for($i = 0; $i &lt; (count($word_array)/2); $i = $i + 1){ for($j = count($word_array); $j &gt; (count($word_array)/2); $j = $j - 1){ </code></pre> <p>Given "amanaplanacanalpanama", look at what you're doing: </p> <p>comparing, step by step (btw, you're off by 1 on the initializer for $j... <code>$word_array[count($word_array)]</code> is pointing at the 'm' in panama, not the 'a'.): </p> <pre><code>a eq to a? j is 22 i is 0 scan_count: -1 count: 1 m eq to a? j is 22 i is 1 m eq to m? j is 21 i is 1 scan_count: 0 count: 2 a eq to a? j is 22 i is 2 scan_count: 1 count: 3 </code></pre> <p><code>a eq to a</code> is fine, and matches... m is found on the next iteration, but when you get to the next 'a', you're finding the original 'a' at the end of panama... </p> <p>As a side note, since you are starting over from the very end every time, it would be horribly inefficient <code>O(n^2)</code> given a sufficiently large string... </p> <p>Obligatory solution:</p> <pre><code>$word = "amanaplana canalpan ama"; $j = strlen ($word)-1; $pal = true; for ($i = 0; $i &lt; strlen($word)/2; ++$i, --$j) { // skip spaces while ($word[$i] === " ") {$i++;} while ($word[$j] === " ") {$j--;} echo "$word[$i] eq $word[$j]?\n"; if ($word[$i] !== $word[$j]) { $pal = false; break; } } if ($pal) print "yes"; else print "no"; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload