I was wondering what the quickest way would be to do something like the following:
if ($var == 1) {
// 1
}
if ($var == 2) {
// 2
}
if ($var == 3) {
// 3
}
etc, but then at the end having something like:
if ($var != 1 or 2 or 3) {
//Not a number
}
I was thinking about having an if(in_array(...)) statement at the end, but wanted to know your thoughts.
I would do this with a switch
switch ($var) {
case 0:
echo "var equals 0";
break;
case 1:
echo "var equals 1";
break;
case 2:
echo "var equals 2";
break;
default:
echo "var is not 0 1 or 2"
}
Also if you miss out a break statement then you can easily do a case when $var == 1 || $var == 2, read more
If all you want to know is whether "$var" is in your set {1, 2, 3}, then in_array is fine.
Otherwise, if you want to know which (if any) value you've got, then I'd do this:
if ($var == 1) {
// 1
}
else if ($var == 2) {
// 2
}
else if ($var == 3) {
// 3
}
else {
}
Note the "else if" to save you from re-checking what you already know.
Note, too, that PHP 4 and 5 also have a "switch" case/block:
switch ($i) {
case 1:
// 1
break;
case 2:
// 2
break;
case 3:
// 3
break;
default:
...
}
Or use a switch case, this better to read for much cases:
switch($var) {
case 1: /*1*/ break;
case 2: /*2*/ break;
case 3: /*3*/ break;
default: /*not 1 not 2 not 3*/
}
Use if/else if/else, with which you can decide whether strict or loose comparisons are appropriate.
With switch, it's always loose comparisons, which is why I prefer the if statement, since it makes it explicit what mode has been chosen.
if ($var === 1) {
// 1
}
else if ($var === 2) {
// 2
}
else if ($var === 3) {
// 3
}
else {
//neither 1, 2 nor 3
}
Related
I need to implement 3 'if conditions' in my script, i've looked it up online but I can only find solutions up to 2 if's like below
<?
if (condition 1){
do something;
}
elseif (condition 2){
do something else;
}
else {
do this last;
}
?>
but I would need something like this:
if (condition 1) { do this };
else if (condition 2) {do that};
or else if (condition 3) {do that};
else (do this)
How do I go about this?
simply
if(condition){
}
else if(condition){
}
else if(condition){
}
else{
}
you can use switch case statements too. you can use else if as many as you want. Each condition inside if() can accept OR and AND operators as || for OR and && for AND you can use.
if (condition 1) { do this
} else if (condition 2) {do that
} else if (condition 3) {do that
} else { do this }
alternatively if you want to check one variable each time you can use a switch for example
$myvar = 5;
switch($myvar){
case 1:
//do this
break;
case 2:
//do that
break;
case 3:
//do that
break;
default:
//do this
}
You can use this construction
if ( $a == $b ) {
// something...
} else if ( $a == $c ) {
// something...
} else if ( $a == $d ) {
// something...
} else {
// otherwise...
}
But if all of the conditions are ( $a equals to something ) it's better to use switch ... case:
switch ( $a ) {
case $b:
// something...
break;
case $c:
// something...
break;
case $d:
// something...
break;
default:
// otherwise...
break;
}
Solution 1
Using many elseif statements as you want.
Use this solution when your conditions are complex, or comparing different variables.
if (/*condition 1*/) {
// Action to condition 1
} else if (/*condition 2*/) {
// Action to condition 2
} else if (/*condition 3*/) {
// Action to condition 3
} else if (/*condition n*/) {
// Action to condition n
} else {
// Action when no conditions match.
}
Solution 2
Using switch statement:
Use this condition when you want to compare a variable against constant values:
switch ($age) {
case 0:
return 'You are a baby';
break;
case 18:
return 'You are 18 years old';
break;
case 21:
case 22:
case 23:
return 'You are too old';
default:
return 'Unexpected age :(';
}
How about using the or operator, ||:
if (condition 1) { do this }
else if (condition 2 || condition 3) {do that}
else {do this}
An example:
<?php
function testCondition($a, $b) {
if ($a == $b) {
print ("They are the same<br />\n");
}
else if ($a == "a" || $b == "b") {
print ("One is the same as its letter<br />\n");
}
else {
print ("They are some other sort<br />\n");
}
}
testCondition("c","c");
testCondition("a","c");
testCondition("a","b");
testCondition("d","e");
?>
Outputs:
They are the same
One is the same as its letter
One is the same as its letter
They are some other sort
I have the same problem as first stated here. I have four variables but the second one is skipped and only 1,3, and 4 work. Why?
if(empty($fromName) or empty($fromEmail) or empty($subject) or empty($comments)) {
echo 'You cannot submit the form with empty fields. Please correct the form and resubmit.';
return false;
}
elseif($fieldDelete == "Delete this text!"){
echo "Delete the contents of the fourth field before submitting.";
return false;
}
elseif (($fromName == "Curtisvien") || ($fromName == "Thomastymn") || ($fromName == "RichardMark")) {
echo "Failed. Please try again.";
return false;
}
else {
$flgchk = mail ("$to", "$subject", "$message", "$headers");
$imgfile = "images/NatMap logo2.gif";
$handle = fopen($filename, "r");
$imgbinary = fread(fopen($imgfile, "r"), filesize($imgfile));
echo '<img src="data:image/gif;base64,' . base64_encode($imgbinary) . '" width=427 height=72 />';
echo "\n<br />\n<br />Thank You! An e-mail has been sent to the National Map web team and they will get back to you in the next 24-48 hours.";
}`enter code here`
For the following php program with a switch statement, why '' give me $vSS=2 instead of =1?
Quite strange to me. I am using PHP 5.5.9.
I can add case '': to resolve the problem, but I am curious why PHP give $vSS=2 instead of
$vSS=1. Is it normal or a bug?
<?php
R(15); // 1 ok
R(''); // why give me 2
R(40); // 2 ok
R(70); // 3 ok
#
function R($SS){
switch($SS){
case $SS<=20: $vSS=1;break;
case ($SS>20 and $SS<=49.9): $vSS=2; // why here?
if($SS == '') echo "DEBUG: SS is a null string.<br>\n";
break;
case ($SS<=100 and $SS>49.9): $vSS=3; break;
default:$vSS=0 ;
}
echo "DEBUG:(SS/vSS) $SS:$vSS\n";
}
?>
------ RESULT
DEBUG:(SS/vSS) 15:1
DEBUG: SS is a null string.<br>
DEBUG:(SS/vSS) :2
DEBUG:(SS/vSS) 40:2
DEBUG:(SS/vSS) 70:3
You don't understand how switch works. It compares the value in switch($SS) with each of the case values, it doesn't just test each case. So
switch ($SS) {
case $SS<=20:
is similar to:
if ($SS == ($SS<=20))
The reason the second case is being executed is because ($SS > 20 && $SS <= 49.9) is false, and false is considered equal to zero or an empty string.
You shouldn't use switch for what you're doing, you should use if/then/elseif/else:
if ($SS <= 20) {
$vSS = 1;
} elseif ($SS <= 49.9) {
$vSS = 2;
} else {
$vSS = 0;
}
#Barmar is right, expression in case() is compared to switch(something_here) but you don't have to cahnge your all your code to if/elsif/elsif/.../... logic. Just change switch() statement to true
switch(true) { // <-- this part only
case $SS<=20:
$vSS=1;
break;
case ($SS>20 and $SS<=49.9):
$vSS=2; // why here?
// must not be here
// if($SS == '') echo "DEBUG: SS is a null string.<br>\n";
break;
case ($SS<=100 and $SS>49.9):
$vSS=3;
break;
case $SS=='': // you can check it here
echo "DEBUG: SS is a null string.<br>\n";
break;
default:
$vSS=0 ;
}
Thats the code:
switch (true)
{
case (isset($_REQUEST['a']) && is_numeric($_REQUEST['a']) && ($_REQUEST['a'] > 0)):
case (isset($_REQUEST['b']) && is_string($_REQUEST['b']) && in_array($_REQUEST['b'], $barray)):
case (isset($_REQUEST['c']) && is_numeric($_REQUEST['c']) && ($_REQUEST['c'] > 0) && ($_REQUEST['c'] <= $cbase)):
try { echo "Foo"; }
catch(Exception $e) { echo $e->getMessage(); }
break;
default:
echo "Bar"; break;
}
I'm wondering if these are allowed for use in switch cases?
Very soon I must use switch because of many comparisons and willing to try it. In this case 3rd case gives me always correct output, even when $_REQUEST['c'] is bigger than $cbase, while should fall to default :|
Yes this is valid. Using switch(TRUE) enables you to have strict comparisons in a switch statement. check this examples:
Not typesafe:
$a = '1';
switch($a) {
case 1 :
// do something (will get executed)
break;
case '1' :
// do something:
break;
}
Better:
$a = '1';
switch(TRUE) {
case $a === 1 :
// do something; (will not get executed)
break;
case $a === '1' :
// .. do something;
break;
}
Also this usage allows for more complex case statements, like this:
switch(TRUE) {
case strpos($input, 'a') === 0 :
// do something
break;
case strpos($input, 'b') === 0 :
// do something
break;
}
I need to do multiple checks for a variable. I've seen an "Equals" example, here: w3schools.
But they are two different variables. Right now I have:
if ($color == 'blue')
{
//do something
}
But I need to to multiple checks for $color. Eg if it equals red or green too. How is this written?
As simple as:
if ($color == 'blue' || $color == 'red' || $color == 'green') {
//do something
}
There are several other options. Using switch operator:
switch ($color) {
case 'blue':
case 'red':
case 'green':
//do something
}
Or more complex using in_array function:
$colors = array('blue', 'red', 'green');
if (in_array($color, $colors)) {
//do something
}
Use a switch-statement.
switch($color)
{
case "blue":
// do blue stuff
break;
case "yellow":
// do yellow stuff
break;
case "red":
// do red stuff
break;
default:
// if everything else fails...
}
In case you want to do the same thing on all colors, just use the || (boolean or) operator.
if ($color == "blue" || $color == "red" || $color == "yellow")
{
// do stuff
}
You can also go with preg_match on this one. This might be overkill, but I'm sure it's very fast!
$color = "blue";
$pattern = "/^red|blue|yellow$/";
if ( preg_match($pattern,$color) ) {
// Do something nice here!
}
Basically, I always use words 'and' & 'or' so, my scripts look like:
if ($value == '1' or $value == '2' or $value == '3') {
//do stuff
}
if ($value == '1' and $user_logged == 'Admin') {
//do stuff
}
It's possible get rid of of $value repeating?
Any benefit in using and and or instead of || and && ?
There is no way to shortcut expressions like
if ($value == 1 or 2 or 3) // invalid
But you can check the values in another way:
if (in_array($value, array(1, 2, 3))) {
// do stuff
}
The difference between or and || is operator precedence. Use || and &&, not or and and.
Answer 1.
$inArray = (1,2,3);
if (in_array($value,$inArray)) {
// do stuff
}
Answer 2.
Operator precedence
You can use first if as a switch statement:
switch($value) {
case "1":
echo "value is 1";
break;
case "2":
echo "value is 2";
break;
case "3":
echo "value is 3";
break;
}
Answer to your second question: Operator precedence