Breaking out of this while statement...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Breaking out of this while statement...

Post by neophyte »

Okay I need to figure out how to break out of this while statement. I'm searching the file $comparefile for a duplicate link ($newlink). The script executes and then stops when $newlink != $word. But I need to be able to break out to send an error message when a match is found. Thanks.

Code: Select all

$fp = fopen("templates/links.txt", 'r');
		$comparefile = fgets($fp);
		$delims = """";
		$word = strtok($comparefile, $delims);
		while (is_string($word) &&  $newlink != $word ){
			if ($word){
			print "$word <br>";
			//C an't figure out where to put this. print "Link has already been used.";
			&#125;
			$word = strtok($delims);
			&#125;
User avatar
DuFF
Forum Contributor
Posts: 495
Joined: Tue Jun 24, 2003 7:49 pm
Location: USA

Post by DuFF »

Break out of it then :D
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Dude man

Post by neophyte »

Like if I knew how to break; out I would do it.... :lol:

Hopless lost newbie....

Give a dog a bone?
User avatar
DuFF
Forum Contributor
Posts: 495
Joined: Tue Jun 24, 2003 7:49 pm
Location: USA

Post by DuFF »

I guess you could just do this?

Code: Select all

<?php
$fp = fopen("templates/links.txt", 'r');
      $comparefile = fgets($fp);
      $delims = """";
      $word = strtok($comparefile, $delims);
      while (is_string($word))  {
         if($newlink == $word)
         {
              echo "Link has already been used."
              break 2;  //break out of the if statement and the while statement
         }
         if (!empty($word))  {
              print "$word <br>";
         }
         $word = strtok($delims);
      }
?>
There are many other ways to avoid this, you rarely see "break" used.

Code: Select all

<?php
      if($newlink == $word)  {
          echo "Link has already been used."
      }
      else  {
		  while (is_string($word) &&  $newlink != $word ){
			if ($word){
			print "$word <br>";
			}
			$word = strtok($delims);
		  }
      }
?>
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

THANKYOU FOR THE BONE!

Post by neophyte »

Thanks Duff the code worked great! But I'm sure that's no suprise. I was so close I could smell it. MMMMMMMMM SILICONE! I knew the elements I needed but didn't quite know how to make it come together.....

You da man,

Thanks! :D
Post Reply