Logan Butler Logan Butler - 1 month ago 12
PHP Question

Continue statement inside while loop for search page feature

I don't understand why this loop isn't working.

This loop's purpose is simply just to skip every value of the array (in this example, 0-2) that's not equal to the given search term (in this example, TN). So the output should be

TN


and shouldn't be

IN
TN
OH


Here's my code:

<?php

$states = array('IN', 'TN', 'OH');
$search = 'TN';

$count = 0;
while($count <= count($states)){
if($states[$count] != $search){
continue;
}

echo $states[$count]."<br/>";
$count++;
}

?>

Answer

move the count++ so it always increments and be optimistic:

while($count < count($states)){
  if($states[$count] == $search){
    echo $states[$count]."<br/>";
  }
  $count++;
}