conditional while loop in php? - php

I need to do a PHP while loop, but only if a variable is true. And I can't really put the while loop in an "if" statement, which seems like the obvious thing to do, since the code block is huge and it would be ugly and confusing. Do I need to break out the code in the loop into a function, or is there an easier way to deal with this?
Here's the basic idea:
if(condition){
while(another_condition){
//huge block of code loops many times
}
} else {
// huge block of code runs once
}
I want the huge block of code to execute regardless of the state of the condition variable-- but only to execute once if condition is false, and execute for as long as another_condition is true if condition is true.
The following code doesn't work, but gives an idea of what I want to accomplish:
if(condition){ while(another_condition){ }
// huge block of code
if (condition){ } } // closes the while loop-- obviously throws an error though!
thanks in advance.

If I understood your problem correctly, you could use the do ... while() structure:
do
{
// your code
} while(condition);
This will execute // your code once regardless of any factor, and then only for the second iteration and those after will it check for the condition.

For readability if your huge block of code can be separated in several specialized functions, do it. It will surely pay out if you need to debug later.

I would put the huge block of code in a function so it can be used again without having duplicate code.
function hugeBlockOfCode() {
// Huge block of code.
}
while (condition && another_condition) {
hugeBlockOfCode();
}
if (!condition) {
// Run code once.
hugeBlockOfCode();
}
or
do {
hugeBlockOfCode();
} while (another_condition);

Is this kind of what you are looking for?
while (condition && another_condition) {
// large block of code
}
if (!condition) {
// do something else
}

Related

End a php tag without die() or exit()

I was wondering if PHP has a function that allows me to end a process before it reaches the "?>" tag, example:
<?php
echo 'first';
endphptag();
echo 'second';
?>
third
<?php
echo 'fourth';
?>
Then the output should be:
first
third
fourth
I know that some people consider this as something useless, but I want to do it for a validation script on an iframe instead of use the die or exit function because it kills the whole script, I just want to end a part of it.
Normally I use if - else instead, but I want to avoid them because the processes are large and I want something more readable, by the way I use if - die in my ajax scripts and I want to use something like this in my iframes too, Thank's!
Well, I just wanted to know if PHP already had a proper function for it (it seems not), so I think I will just leave it with if - elses, because is not really worth to use more process for make it "more readable" (ex: try - catches uses too much resources, I'm not going to go-tos neither). My doubt was only for that, I will only use this procesdure in my ajax files using the die function (I don't know if it is recommended, but I think there's no problem because PHP should have it for some reason)
Exceptions is what you are looking for:
try {
// code
} catch (Exception $e) {
// handling
}
You put your code inside the try block and you end it throwing an exception with throw new Exception();, and it exits only the rest of the code inside the try block.
Your code would then be:
<?php
try {
echo 'first';
throw new Exception();
echo 'second';
} catch (Exception $e) {}
?>
third
<?php
echo 'fourth';
?>
I'm going to throw this out there and duck, but if you really need to do this, then goto is actually not a bad option:
<?php
echo 'first';
goto endofblock;
echo 'second';
endofblock:
?>
Or you could avoid the "evil" of goto with a faux-loop. To the compiler they basically look the same, but other programmers won't club you to death for using goto
<?php
do {
echo 'first';
break;
echo 'second';
} while (false)
?>
Why do you not use switches and cases?
http://php.net/manual/en/control-structures.switch.php
If I were you, I would omit the end-php tag. Most coding standards advise against it, for reasons that are too lengthy to explain here.
But that aside, go ahead and use the if/else or the switch/case control structures. Take the large parts of the validation process out of the inline code and package them in functions or class methods if you're using OOP.
See also this note about GOTO ;-) http://xkcd.com/292/
The PHP interpreter works with the file as a single unit, the <?php tag just specifies portions of text (outside the tag) to ignore, just like comments. The tag does not border any portion of code.
So in your case, I think the goto statement might be the right option. Or, if you could put the code into a function, you could use return.

PHP exit, return & proper programming standards

Is it ok to include a break or exit command to prevent further code from executing or is this bad programming?
function index()
{
$error = NULL;
if ($_POST){
// validate form
if ($form_validated) {
echo 'this content only';
exit; // or return IS THIS BAD???
} else {
$error = 'form failed';
}
}
echo 'normal page on initial load';
if ($error) { echo '<br />'.$error; }
}
It is OK to prevent further code from executing using exit.
Having said that, whether this is the best way to do it in this particular example is debatable. It is typical to use exit when issuing redirects:
header('Location: /foo');
exit;
In your case, there doesn't seem to be an immediate need to stop the program execution in mid run. You should rather structure your program flow so it always completes, but with different results. It is hard to follow program logic which may terminate somewhere in the middle, so a more logical flow that returns from functions or branches using if..else is usually preferable.
For the example you give:
function index()
{
...
if ($form_validated) {
echo 'this content only';
exit; // or return IS THIS BAD???
} else {
...
}
This is normally called early exit or early return (return is more common). This can be very okay, some people say that early returns make code hard to understand but I'd say it depends on a lot more if a function can be easily read and understood or not.
So the person who decides here whether it is bad or not is you. You need to find some criteria on your own where you draw the line. For example if a function is long (more than 12 lines of code) and contains many of these early returns or even exits, this will make the code more complicated.
Generally early returns can make a functions code less complex which can heavily reduce the number of bugs.
So probably the complexity is a good criteria here.
Additionally I suggest you use exit very carefully. It does much at once and you should normally not need it within your program flow. Especially if you're writing business logic.

PHP exit() vs if - else statement

Is it a good or bad practice to authenticate and then just exit() the function or to wrap the whole result of the authentication in an if statement? Example
function foo($uid)
{
$allowed = $auth->checkIfAllowed($uid);
if ($allowed == false) exit();
//continue with senstive code here
}
}
OR
function foo($uid)
{
$allowed = $auth->checkIfAllowed($uid);
if ($allowed == true)
{
// do sensitive stuff
}
}
I would like to take this opportunity to talk about exit; (as others have stated both work, the second is more explicit then the first, and give you the opportunity to send a nice error message to the user). My main beef (I have several with exit;) is that people should stop using it in libraries, i.e. code that can/will be used in other projects... You know how irritating it is to debug those? Throw exceptions, trigger fatal errors, but give me something with a description.
/rant
Your examples are equivalent.
However, it's not usually useful to the end user to just exit the script abruptly. Instead, send your user a useful error message printed in HTML rather than the plain text you would get from a die() call, for example.
function foo($uid)
{
$allowed = $auth->checkIfAllowed($uid);
if ($allowed == false)
{
$errormsg = "You are not allowed to view this page";
}
else
{
//continue with senstive code here
}
}
Later, print the error in HTML, rather than just aborting the script:
<div class='error'><?php echo $errormsg; ?></error>
Either or. I don't think it'll make a difference. It relatively the exact same thing. In programming there are many ways to program things, never on right way in most instances.
They are absolutely the same. The indentation and coding style is the only difference. In both cases the sensitive code won't execute unless the authentication is done successfully.
It's usually better to be expressive in your code though, so I'd recommend the second method.

Stopping an if clause along with the whole PHP script, but not HTML

I've been having this problem for around an hour, and have searched the internet for answers. I've checked the PHP documentation, looked around, Googled, nothing.
Anyways, my problem is that after I try to validate something (and it's wrong), if I use exit; it will also stop the HTML after. Here's what I'm talking about:
if ($_POST['exampleEmail'] == "")
{
echo "Please enter an e-mail."; //Now I want only the PHP script to stop, however...
exit; //If I use exit, then the HTML after this script (footer) doesn't show.
}
If anyone can help, please do. I've tried using break, but to no avail, since it's only for loops and switches.
If there is a better/more correct (or simply correct if this is the wrong way), please share. I've had this problem in the past, and I just used exit then.
Thanks.
Just wrap the rest of the script in a new if block:
$execute = true;
// HTML here...
if (empty($_POST['exampleEmail'])) {
echo "Please enter an e-mail.";
$execute = false;
}
// HTML here...
if ($execute) {
// do stuff only if execute is still true.
}
// HTML here...
Now that this is working for you, I advise you to do some research into separating your presentation and your logic. There's a lot of tutorials and blogs on the subject, you just need to start searching.
You should use an if-statement in PHP
if ($_POST['exampleEmail'] == "")
{
echo "Please enter an e-mail.";
$stop_script = true; //stop the script
}
else $stop_script = false; //or continue the script
if($stop_script === false)
{
//php scripts
}
//html
Use break http://php.net/manual/en/control-structures.break.php instead. But you probably have a structural Problem if it comes to this usecase in the first place.

How to halt execution of current PHP script?

I'm writing some simple PHP to back up a microsite. In my controller, I have a quick security/sanity check
if(!preg_match('/^[a-z]$/i', $req)) { gohome(); }
I'd like to continue my the main code after this, but for aesthetics, I'd like to avoid putting the rest of it inside the else block. What's the best way around this? I can think of setting up a fairly simple wrapper to handle authentication and security logic, but I feel like I just missed a really simple solution in my training.
You can use the die/exit function to end the script with (or without) an error.
You could
return gohome();
or
throw new Exception('Request may only contain letters');
Either will stop the execution of that particular script at that point.
If this is in a function, you can usually just return early.
Try the following.
preg_match('/^[a-z]$/i', $req) or die("exit message here, if you'd like");
It's no better functionally than Xavier's but I just like the syntax/idea of "do this or DIE" :) Also kind of makes me think of those old Nintendo games Skate Or Die and Ski Or Die.
exit() is a pretty good way to terminate the current script...
if(!preg_match('/^[a-z]$/i', $req)) { gohome(); exit() }
I prefer to keep exit()/die() calls in the main flow. Or as Phil suggests, throw an Exception and exit() somewhere lower in the stack
You can quite simply just write;
return;
The command will return program control to the calling script, so;
If linear code in an included PHP file, the control will return to the script that invoked the running of that file.
If in a function (or object method) the function will immediately return the argument if supplied, and null if not.
It will not stop the running of the script completely (you need to use exit or die for that) unless there is no calling script.
So in your case;
if(!preg_match('/^[a-z]$/i', $req))
{
gohome();
return;
}
and the else block is not required since it will only continue the script if the condition returns false.

Categories