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.
Related
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
}
Can I write a switch statement like this?
switch ($mood) {
case hungry :
case sad :
echo 'Eat a chocolate';
case sad :
echo 'Call Up your friend';
}
Is this a good practice?
EDIT : Removed the break statement, based on the comment.
It is technically possible to define multiple cases with the same value, but only the first case will get executed. So it's pretty much useless.
From the switch() documentation:
PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement.
Since the first case has a break in it, further cases won't be executed and the code will exit the switch() block.
Consider the following piece of code:
$var = 'sad';
switch ($var) {
case 'sad':
echo 'First';
break;
case 'sad':
echo 'Second';
break;
}
This will output First.
If you want to execute multiple statements if a condition is TRUE, then add them under the same case, like so:
switch ($var) {
case 'sad':
echo 'First';
echo 'Second';
break;
}
I'm using switch statement on $_POST method and my script runs correctly but I think my code is not in a right way.
Here's my code:
<?php
switch(isset($_POST))
{
case isset($_POST['A']):
//do something
break;
case isset($_POST['B']):
//do something
break;
case isset($_POST['C']):
//do something
break;
}
?>
my script runs correctly but I think my switch statement is not GOOD enough. Is there more simplier way or BETTER way using switch statement and $_POST method?
It's horrible but I prefer this than if-else-evil-chain:
switch(true)
{
case isset($_POST['A']):
//do something
break;
case isset($_POST['B']):
//do something
break;
case isset($_POST['C']):
//do something
break;
}
check this out ;)
if (!empty($_POST)) {
switch ($_POST) {
case $_POST['A']:
#do something;
break;
case $_POST['B']:
#do something;
break;
case $_POST['C']:
#do something;
break;
}
}
Maybe you mean something similar?
<?php
if(isset($_POST['A'])){
// do something
}
if(isset($_POST['B'])){
// do something
}
if(isset($_POST['C'])){
// do something
}
?>
(This executes all the different matching branches instead of only the first one. Change the non-first if's to elseif if you want execute only the first matching branch.)
A nice way of putting a switch (){ case: } method is:
if (condition){
// Do Something
}elseif(condition){
// Do Something
}elseif(condition){
// Do Something
}
This chain, is horrible to look at, but something I would suggest using in your unique case, alternativley you could go with #lame-up-ducks answer, but this is what i'd personally recommend using
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.