In pick basic there is a case command which functions similar to the switch command basically doing nested if then else commands. The code is like this:
begin case
case a=4;do something
case b=5 or c=6;do something
case y=x and f=z;do something
case 1;do something
end case
if any of the conditions are true, it falls into that case. I know PHP has the switch command, but that is limited to the value of one variable. Is there a way to code the above in PHP or javascript for that matter without a bunch of if then else commands similar to the above?
If you really don't want to use if/else, then switch (true) can work:
switch (true) {
case ($a === 4):
doSomething();
break;
case ($b === 5 || $c === 6):
doSomething();
break;
case ($y === $x || $f === $z):
doSomething();
break;
default:
break;
}
However, it is less typing, and it makes your code more readable, if you simply use if/else instead, just as Shomz suggested. I really wouldn't recommend using switch (true).
Replacing case with else if is only 3 bytes longer, I don't see the big deal because that is exactly what the if/else is for. Switches are used for single variables, as you said.
Your do something could also include a result variable or a flag that will be set if any of the conditions are met.
So this:
begin case
case a=4;do something
case b=5 or c=6;do something
case y=x and f=z;do something
case 1;do something
end case
could be:
var case = false;
if (a==4) {dosomething(); case = true}
else if (b==5 || c==6) {dosomething(); case = true}
else if (y==z || f==z) {dosomething(); case = true}
else if (1) {dosomething(); case = true} // supposedly the default case?
Related
I have the following if statement (except the final one would be much longer with more values) that I would like to condense.
if ($row['titleId'] == '123' || $row['titleId'] == '456' || $row[){
I would imagine it would end up something like:
if ($row['titleId'] == ('123'||'456'){}
Or would I be better off like this:
$array = ('123','456')
if (in_array($row['titleId'], $array){}
You can use switch for this:
switch ($row['titleId']) {
case '123': case '456': case '789': case '314': case '271':
doSomething();
}
I'd probably still prefer to have each case on a separate line but, if your goal is to reduce the "height" of your code, you can do it as above.
In terms of shortening the code in your comment, which apparently looks like this:
switch($row['titleId']){
case '8216': case '8678': case '8705': case '8216': case '8707':
$rows[$row['titleId']]=array();
break;
case '8214':
$rows['8216'][]=$row['titleId'];
break;
case '8791':
$rows['8678'][]=$row['titleId'];
break;
case '8643':
$rows['8705'][]=$row['titleId'];
break;
case '8666':
$rows['8707'][]=$row['titleId'];
break;
}
you could opt for something like:
$xlat = array('8214'=>'8216', '8791'=>'8678', '8643'=>'8705', '8666'=>'8707');
switch($row['titleId']){
case '8216': case '8678': case '8705': case '8216': case '8707':
$rows[$row['titleId']]=array(); break;
default:
if (array_key_exists($row['titleId'],$xlat)) {
$rows[$xlat[$row['titleId']]][]=$row['titleId'];
}
}
This compresses the common cases by putting them under the control of an associative array. Basically, if the title ID is in the array as a key, its lookup value will be used to affect the correct $rows entry.
I have a switch statement with 3 cases,like this:
switch($date) {
case 1:
echo "";
break;
case 2:
echo "";
break;
case 3:
echo'';
break;
default:
echo '';
break;
}
And i am wondering,if there is a way to loop through all cases if they are all true.But with using break,because if i am not using it,the cases wont work properly.So is there a way???
You shouldn't use switch if you want to see if multiple things are true about the variable in question since the switch statement will cut out once one of the cases holds true (i.e. it won't continue to look to see if the other cases also apply to the variable).
If your goal is to test if multiple things are true regarding a variable, just use an if statement:
if ($date == X && $date == Y && $date == Z) {
// Do something since all the conditions are met
}
Another possibility is to "fall through" your cases like this:
switch ($variable) {
case 0:
// Do something to (some) variable to indicate this case applies
case 1:
// Do something to (some) variable to indicate this case also applies
case 2:
// Do something to (some) variable to indicate this case also applies
echo "WHATEVER YOU WANT TO ECHO"
break;
}
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
}
I'm really just curious about this, and I don't plan on implementing it, but I do think it would be a cool control structure to use should the appropriate conditions arise.
I have an array of booleans that represent which types of data a user is trying to see and then I have an object of booleans saying if a user has permission to see that data or not.
Instead of a list of if statements saying if(permission and display){show this type}, I thought I would instead just use a switch(true) and actually write the same amount of code but formatted a bit nicer, if only I could get a switch statement to continue; .. that would have been cool.
switch(true){
case ($processPermissions->history->view) && ($display['history'] !== false):
$application['history'] = $this->getHistory();
continue;
case ($processPermissions->notepad->view) && ($display['notepad'] !== false):
$application['notepad'] = $this->notepad('get');
continue;
case ($processPermissions->documents->view) && ($display['documents'] !== false):
$application['documents'] = $this->documents('get');
continue;
case ($processPermissions->accounting->view) && ($display['accounting'] !== false):
$application['accounting'] = $this->accounting('get');
continue;
case ($processPermissions->inspections->view) && ($display['inspections'] !== false):
$application['inspections'] = $this->inspections('get');
continue;
case ($processPermissions->approvals->view) && ($display['approvals'] !== false):
$application['approvals'] = $this->approvals('get');
continue;
}
In reality, I'm just going to create an array and loop through that since the code is identical for each case.
..But I'm very curious about how I would be able to get this to work, if I wanted.
seems like a lot of pointless repetition, when you could have something like
$stuff_to_check = array('history', 'notepad', 'documents', 'accounting', etc....)
foreach($stuff_to_check as $thing) {
if ($processPermissions->$thing->view && ($display[$thing] !== false))
$applications[$thing] = $this->document('get');
}
}
It's already supported - just don't include the break statement and every case block after the one that matched will be executed as well, until a break is encountered.
Also, the continue statement is already supported in switch blocks in PHP, but its behaviour is similar to break.
See the documentation for switch for more details.
$value = 2;
switch ($value) {
case 0:
// not executed
case 1:
// not executed
case 2:
// executed
case 'whatever':
// executed
break;
case 'foo':
// not executed
break;
default:
// not executed
}
See the documentation for switch for more details.