Jump to content

Recommended Posts

I remade i little ajax gethint system for learning purposes, i made that if typed name is exactly like in array it prints a message. But...

 

<?php

$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

$q=$_GET["q"];


if (strlen($q) > 0)
{
for($i=0; $i<count($a); $i++)
{
	if ($a[$i] == $q) {
		$response = "Okay";
	} else {
		$response = "not okay";
	}
}
}

echo $response;
?>

 

 

The problem is that it always says "not okay", because it's continue looping even if they match. If after $response = "Okay"; i put "return;" its not gonna do printing.

 

Any suggestions?

Link to comment
https://forums.phpfreaks.com/topic/145764-need-help-with-looping/
Share on other sites

First, simplify your loop by using foreach...

 

foreach($a as $key=>$value) {

      if ($a[$key] == $q) {
         $response = "Okay";
      } else {
         $response = "not okay";
      }
} 

 

Try this, tell me if this helps...

It is better practice to use a foreach for arrays because it's slightly faster and is pretty much the standard way of iterating through an array.  Actually an array is the only thin you can use for a foreach.

 

Anyway, even with the foreach ILMV, if it doesn't match the last name the $response will always be "not okay".

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.