Page 1 of 1

correct use of break in 'if' loop question

Posted: Mon Sep 13, 2010 12:27 pm
by seezee
I have an if loop like this:

Code: Select all

if($zip!=""){
	if(preg_match('/^\d{5}(-\d{4})?$/',$zip)){
		break 2;
		} else {
		$errors=1;
		$error.="<li>Please enter a valid <abbr>us</abbr> ZIP code (5 digit ZIP or ZIP + 4)</li>";
	}
}
But when I input a valid (matching) string, I get an error: PHP Fatal error:
Cannot break/continue 1 level in path/to/file.php on line xyz
I've worked around this with

Code: Select all

if($zip!=""){
	if(preg_match('/^\d{5}(-\d{4})?$/',$zip)){
		$errors=$errors;
		} else {
		$errors=1;
		$error.="<li>Please enter a valid <abbr>us</abbr> ZIP code (5 digit ZIP or ZIP + 4)</li>";
	}
}
But I'd like to understand the correct way to do this.

Thanks,

--cz

Re: correct use of break in 'if' loop question

Posted: Mon Sep 13, 2010 12:38 pm
by bradbury
break ends execution of the current for, foreach, while, do-while or switch structure but does not end the loop for a if statement.
Hope that helps you out.

Re: correct use of break in 'if' loop question

Posted: Mon Sep 13, 2010 12:38 pm
by bradbury
btw the php manual should be your best friend. I pulled that straight from the manual after searching break.

Re: correct use of break in 'if' loop question

Posted: Mon Sep 13, 2010 1:09 pm
by AbraCadaver
This is functionally the same and probably cleaner and more to the point:

Code: Select all

if(!empty($zip)){
        if(!preg_match('/^\d{5}(-\d{4})?$/', $zip)){
                $errors = 1;
                $error .= "<li>Please enter a valid <abbr>us</abbr> ZIP code (5 digit ZIP or ZIP + 4)</li>";
        }
}
And really, you can use $error as an array and then use count($errors) later to see how many:

Code: Select all

$error = array();
if(! empty($zip)){
        if(! preg_match('/^\d{5}(-\d{4})?$/', $zip)){
                $error[] = "<li>Please enter a valid <abbr>us</abbr> ZIP code (5 digit ZIP or ZIP + 4)</li>";
        }
}
$errors = count($error);

Re: correct use of break in 'if' loop question

Posted: Mon Sep 13, 2010 1:11 pm
by seezee
Thanks, Bradbury. I did RTFM, but that distinction escaped me as I was doing a lot of skimming. :-)

Re: correct use of break in 'if' loop question

Posted: Mon Sep 13, 2010 5:08 pm
by seezee
Abracadaver,

Of course, you're right. I actually figured that out on my own after my last post.