Jump to content

If...else problem


RichieW13

Recommended Posts

I have a simple text file called bio.txt:

wohlersr; Richie Wohlers; Intermediate; Four Aces
meyersg; Greg Meyers; Novice; Four Aces

 

I wrote a little script, to return the info for Greg Meyers if the user id is correct, or say "Member not found" if incorrect.  For some reason, my output is giving me both.  I assume it's a context error, but can't figure it out.

 

Here's my script:

<?php
$file=file("bio.txt");
$count=count($file);

$i=0;
while($i<=$count)
{
$row = explode(";", $file[$i]);

$id = $row[0];
$name = $row[1];
$class = $row[2];
$club = $row[3];

if($id=="meyersg"){
	echo $name."</br>";
	echo $class."</br>";
	echo $club."</br>";
}else{
	echo "Member not found.";
} 

$i++;
}

?>

 

And here's the output I'm getting:

Member not found. Greg Meyers
Novice
Four Aces
Member not found. 

Link to comment
https://forums.phpfreaks.com/topic/245790-ifelse-problem/
Share on other sites

You put that output inside the loop. It will print the message according to each line; the first line does not match but the second does.

 

Go through the entire file before making any found/not found judgments.

$info = null;
for each line in the file {
    if the line matches some criteria {
        $info = this line
        break; // found it, can stop early
    }
}
if ($info == null) {
    // not found
} else {
    // found
}

Link to comment
https://forums.phpfreaks.com/topic/245790-ifelse-problem/#findComment-1262427
Share on other sites

EDIT:requinix beat me to it, but I have additional useful info, so I'll leave this post anyway.

 

You have an array - use foreach() instead of while() with a variable you have to increment. Your while() condition is

while($i<=$count)

and $i starts at 0.

 

So, if the file contains 10 lines you start with $i = 0 and continue the loop while $i <=10. That would mean the loop would go 11 times. That extra iteration will lead to problems.

 

The specific problem is that you have to process the WHOLE file before you can determine that it was not found!

 

$search_id = "meyersg";

$file = "bio.txt";
$lines = file(file);

$member_found = false;
foreach($lines as $line)
{
   $row = explode(";", $line);

   if($row[0]==$search_id)
    {
        $member_found = true;
      echo "{$row[1]}</br>{$row[2]}</br>{$row[3]}</br>\n";
   }
}

if(!$member_found)
{
    echo "Member not found.";
} 

Link to comment
https://forums.phpfreaks.com/topic/245790-ifelse-problem/#findComment-1262429
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.