I have a simple system for search and compare results.
In this case I'll have 2 results ok and one bad.
For use this I use the following code:
for ($i=0;$i<sizeof("search.txt");$i++)
{
if ($_REQUEST['search']=="ok" && $_REQUEST['car']=="")
{
print "ok";
break;
/// show results;
}
if ($_REQUEST['search']=="ok" && $_REQUEST['car']=="" && $_REQUEST['city']=="")
{
print "ok";
break;
/// show results;
}
}
The problem it's if the result must show 2 results, the line "break" stops the loop, but if I don't put break, it shows me results of other conditional "if", I put simple example, because into this loop I have many conditionals "if", by this I need to show all results in each case and break for each conditional, but break cur me the loop into the loop and no let continue
My question is if I can use break for do or need use other function let me do this, because I need do by this way
Thanks Regards
break is intended for case statements and loops. Since you're not using a case, the break will break the foreach. You probably want continue to move on to the next iteration.
e.g.
for(...) {
if (something) {
...
continue; // "break" this loop iteration and move on to the next one.
}
if (something else) {
...
break; // kills the foreach and moves down to the "stuff after loop" below.
}
switch (this_and_that) {
case 'a': ...; break; // breaks out of the switch and moves to "stuff after switch"
case 'b': ...; break; // ditto
}
... stuff after switch ...
}
... stuff after loop ...
I would make it this way:
if ($_REQUEST['search']=="ok" && $_REQUEST['car']=="")
{
print "ok";
if ($_REQUEST['city']=="")
{
break;
}
break;
}
because once first if-statement is true, the second will only need 'city' to be true.
Related
I am wondering how to jump back outside a switch statement if a certain case is met, as the code will have to retry what it has just done. Here an example of my code;
$result = $this->check($user, $password);
switch($result){
case 'invalid-email-password':
//Do stuff
break;
case 'error':
//Do stuff
//Jump back to $result = $this->check to try again
break;
The code should only continue when the 'error' case is no longer the result of the $this->check() function.
In general, if you want to program a "retry until it works" thing, consider this:
while(true) {
doSomething();
if( $it_worked) break;
}
Note that since you're in a switch statement, you will need to use break 2; on a successful result to exit out of both the switch and the while.
To prevent an infinite loop, you can have an $attempts counter that counts down and breaks the loop manually if you run out of tries.
Here is my code I wanted to ask if there is a better way to do this? I'm going to need more "else if" options and I'm worried about performance
if($_GET['begin'] === 'yeg'){
} else if ($_GET['begin'] === 'deda') {
} else if ($_GET['begin'] === 'beara') {
} else if ($_GET['begin'] === 'eima') {
} else if ($_GET['begin'] === 'aba') {
}
You should use switch statement instead. A switch construct is more easily translated into a jump (or branch) table. This can make switch statements much more efficient than if-else when the case labels are close together. The idea is to place a bunch of jump instructions sequentially in memory and then add the value to the program counter. This replaces a sequence of comparison instructions with an add operation. - #Judge Maygarden
Why the switch statement and not if-else?
$begin = $_GET['begin'];
switch ($begin):
case 'yeg':
//do something
break;
case 'deda':
//do something
break;
case 'beara':
//do something
break;
case 'eima':
//do something
break;
case 'aba':
//do something
break;
endswitch;
You can try to use a switch statement instead:
switch ($_GET['begin']) {
case 'yeg':
break;
case 'deda':
break;
// Yada yada, continue like this as much as needed.
}
I'm wondering whether it is possible to replicate this kind of check in a switch statement/case:
if(isset($_POST["amount"]) && (isset($_POST["fruit"]))) {
$amount = $_POST['amount'];
$fruit = $_POST['fruit'];
if($fruit == "Please select a fruit") {
echo "<script>alert('Required Field: You must choose a fruit to receive your total')</script>";
} else if(empty($fruit) or ($amount<=0) or ($amount>50)) {
echo "<script>alert('Required Field: You must enter an amount between 0-50g to receive your total')</script>";
} ... and further on
Note: I'm paying more attention to the && comparison that can be done simply in one IF, and whether this is possible to be done in a switch case and receive results like the nested if/else would. If it's not possible, why? and which method would be more efficient and why?
I would rather stick with If-Else If condition rather than converting it to Switch statement.
You have to realize the the switch statement only accepts one parameter:
switch($arg)
In your case you have amount as $_POST["amount"] and fruit as $_POST["fruit"].
Your first problem is how will you pass that 2 values on the switch statement.
You cannot use a switch for this case, since you are checking a condition (isset) of two variables which produces a boolean result. Well actually you could do a switch of this condition and switch in case of true to this code and in case of false to that code. But that would not make much sense imho.
In a switch you can just check ONE variable or expression and in the cases you execute the code of whatever the result of that switch evaluation was.
So no, you cannot do a switch with these nested ifs.
edit: to make this a bit more clear, a swicth is best used when you find yourself using multiple ifs on the same variable:
if ($var < 3)
{
// do this
}
elseif ($var < 6)
{
// do that
}
else
{
// do something other
}
Would be much better written:
switch ($var)
{
case < 3:
// do this
break;
case < 6:
// do that
break;
default:
// do somehting other
}
if i'm looping over an array, and while in the middle of one of the loops i discover some small issue, change ...something..., and need to try again ... is there a way to jump back to the top of the loop without grabbing the next value out of the array?
i doubt this exists, but it would be some keyword like continue or break. in fact, it would be a lot like continue, except that it doesn't get the next item, it maintains what it has in memory.
if nothing exists, can i insert something into the array in such a way that it will become the next key/value in the loop?
maybe this would be easier with a while(array_shift())...
or i suppose a recursive function inside the loop might work.
well, my question is evolving as i type this, so please review this pseudo code:
foreach($storage_locations as $storage_location) {
switch($storage_location){
case 'cookie':
if(headers_sent()) {
// cannot store in cookie, failover to session
// what can i do here to run the code in the next case?
// append 'session' to $storage_locations?
// that would make it run, but other items in the array would run first... how can i get it next?
} else {
set_cookie();
return;
}
break;
case 'session':
set_session();
return;
break;
}
}
i'm sure there is no keyword to change the value tested against in the switch mid-stream... so how should i refactor this code to get my failover?
Not with a foreach, but with more manual array iteration:
while (list($key, $value) = each($array)) {
if (...) {
reset($array); // start again
}
}
http://php.net/each
http://php.net/reset
It seems like a simple fall through would do the trick though:
switch ($storage_location) {
case 'cookie':
if (!headers_sent()) {
set_cookie();
break;
}
// falls through to next case
case 'session':
i'm reading a blog that give something php coding tips.there are two places I don't understand.
less/not use continue.
the structure :
do{
if(true) {
break;
}
if(true) {
break;
}
} while(false);
is better than :
if(true) {
} else if(true) {
} else {
}
can somebody explain why ?
I highly doubt this as a do { } while () is checked every iteration, whereas an if is just a simple comparison.
Maybe the point they were trying to demonstrate in the blog is that a do {} while() loop will pause your code until a condition is met, where as the if statements will be parsed and your code will continue regardless of whether the condition is met or not.