Switch case with three parameters? - php

Is it possible to use three parameters in switch-case, like this:
switch($var1, $var2, $var3){
case true, false, false:
echo "Hello";
break;
}
If not, should I just use if-else or is there a better solution?

The syntax is not correct and I wouldn't recommend it, even if it was. But if you really want to use a construct like that, you can put your values into an array:
switch (array($var1, $var2, $var3)) {
case array(true, false, false):
echo "hello";
break;
}

I would just use the if/else
if($var1 == true && $var2 == false && $var3 == false){
echo "Hello";
}
or
if($var1 && !($var2 && $var3)) {
echo "Hello";
}

You don't have a switch situation here. You have a multiple condition:
if($var && !($var2 || $var3)) { ...

i don't think your syntax is valid.
I'd nest the switch statements.

Another option is to create a function that maps three parameters to an integer and use that in the switch statement.
function MapBool($var1, $var2, $var3){
// ...
}
switch(MapBool($var1, $var2, $var3)) {
case 0:
echo "Hello";
break;
// ...
}

This is the sort of thing that used to be handled by bitwise operators:
if (($var1 << 2) & ($var2 << 1) & $var3) == 4) ...
...back when 'true' was 1.
That being said, the above is concise, but it's pretty hard to read and maintain. Nevertheless, if you have a lot of similar statements, shifting/ANDing might be a way to go to get things under control:
switch (($var1 << 2) & ($var2 << 1) & $var3)) {
case 0: // false, false, false
...stuff...
case 1: // false, false, true
...different stuff...
// all 8 cases if you REALLY care
}

I don't know - if you really want it this way - maybe cast them all to string, concatenate and then use the resulting string in your case condition?

Related

PHP Syntax to shorten if-statements

Disclaimer : the following is a bad practice (but it would be useful in a very, very specific use)
Is there a way to shorten (in a not-so-nice-way-but-shorter) if statements :
instead of :
if(5 == $foo){
$b = 98;
$c = 98 * $otherVariable;
//do something complex
doSomethingElse($b, $c);
}
This example would become shorter, even if it is formatted by an IDE.
It would become something like that (but this does not work):
(5 == $foo) && { $b = 98;
$c = 98 * $otherVariable;
//do something complex
doSomethingElse($b, $c);}
I suggest, you should opt for better readable code, but still if you want to do something different, you may go through below :
($foo == 5) && doSomethingElse(98, 98*$otherVariable);
OR
PHP Ternary Operator
($your_boolean) ? 'This is true' : 'This is false';
You can rewrite your if statement like below :
($foo == 5) ? doSomethingElse(98, 98*$otherVariable) : "";
// little shorter but not better readable
($foo != 5) ? : doSomethingElse(98, 98*$otherVariable);
Test Results:
$ cat test.php
<?php
function aa(){ echo "123\n"; }
$foo = 5;
// this will not call aa()
($foo == 4) && aa() ;
// this will call aa()
($foo == 5) && aa() ;
?>
$ php test.php
123
if(5 == $foo) doSomethingElse(98, 98*$otherVariable);
Look out! The variables $b and $c are not available for further calculations!

Shorthand for else if statment in PHP

I know there is a shorthand for IF/ELSE STATEMENT in PHP such as
($user['permissions'] == 'admin' ? true : false);
But is there a shorthand for ELSE IF statement besides switch?
What you could do
You can keep chaining ternary operators together, e.g.:
$x = $condition1 ? true : ($condition2 ? true : false);
It looks nice now, but once your conditions grow bigger, it quickly becomes unreadable. Note that parentheses are bare essentials for these kind of expressions.
What you should do
Once you add more conditions, prefer to use the proper branching syntax; always assume the person who later has to take over your code is a psychopath who knows where you live:
$canAccess = false;
if ($user['permissions'] == 'admin') {
$canAccess = true;
} elseif ($user['permissions'] == 'whatever') {
$canAccess = true;
}
Yes, you could use an or in the first statement too.
Or, a switch:
switch ($user['permissions']) {
case 'admin':
case 'whatever':
$canAccess = true;
break;
default:
$canAccess = false;
}
I’d rather just use elseif() {} anyway
$somevalue == 'foo' ? 'is foo' : ($somevalue == 'bar' ? 'is bar' : 'is neither');

Php what is the name of this and what does it do?

I'd love to know what this means so I can google it as I see it all the time and it seems to be very useful
(($winstate==1)?'X':'O')
edit: The vars are irrelevant.
Thanks guys
That's called a ternary operator, it's PHP's only ternary operator, and it's shorthand for a conditional:
if($winstate == 1){
return 'X';
}else{
return 'O';
}
It's frequently used when the conditional test results in an assignment or returns something, in this case suppose you wanted to assign 'X' or 'O' to a variable $move, it's far more concise to write:
$move = ($winstate == 1) ? 'X' : 'O';
Look at Comparsion Operators
There's everything explained
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>

php "if" condition mystery

I am running into a funny problem with a mischievous "if" condition :
$condition1="53==56";
$condition2="53==57";
$condition3="53==58";
$condition=$condition1."||".$condition2."||".$condition3;
if($condition)
{
echo "blah";
}
else
{
echo "foo";
}
Why does the if condition pass?
Why does php echo "blah"? What do I do to make php evaluate the "if" statement and print "foo"?
The problem here is that you're putting your expressions in strings!
Your $condition1, $condition2, and $condition3 variables contain strings, and not the result of an expression, and the same goes for your $condition variable which will be a string that looks like 53==56||53==57||53==58. When PHP evaluates a string it considers it true if it is not empty and not equal to 0, so your script will output blah.
To fix this you just need to take your expressions out of the strings. It should look like this:
$condition1 = 53 == 56; // false
$condition2 = 53 == 57; // false
$condition3 = 53 == 58; // false
$condition = $condition1 || $condition2 || $condition3; // false || false || false = false
if ($condition) {
echo 'blah';
} else {
echo 'foo'; // This will be output
}
You're evaluating strings as booleans; they'll aways be true (except the strings "" and "0". Get rid of almost all of the quotes in your program.
Those aren't conditions, they're strings.
$condition1=53==56;
$condition2=53==57;
$condition3=53==58;
$condition=$condition1 || $condition2 || $condition3;
if($condition)
{
echo "blah";
}
else
{
echo "foo";
}
Because you're not checking those variables, it's saying if (String) will always return true. (unless "")
You should be doing:
if(53==56 || 53==57 || 53==58)
{
echo "blah";
}
else
{
echo "foo";
}
All $condition* variables will evaluate to true. This is how PHP sees it:
if("53==56" || "53==57" || "53==58")
What you want is this:
$condition1 = 53==56;
$condition2 = 53==57;
$condition3 = 53==58;
It's because you're evaluating a string, and strings other than empty strings evaluate to true.
You are concatting a string together, a non-empty string equals TRUE in php.
Because when the if passes, $condition is a string (a concatenation of) containing the text of your conditions. Try using if(eval($condition)).
String always evaluate to true if its not empty
And btw php make implicit conversion to boolean

Checking if isset and is true?

Is there a function to check both
if (isset($var) && $var) ?
The empty() function will do the job.
Use it with the not operator (!) to test "if not empty", i.e.
if(!empty($var)){
}
You may use the ?? operator as such:
if($var ?? false){
...
}
What this does is checks if $var is set and keep it's value. If not, the expression evaluates as the second parameter, in this case false but could be use in other ways like:
// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
More info here:
https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator
there you go. that should do it.
if (isset($var) && $var)
if (! empty($var))
It seems as though #phihag and #steveo225 are correct.
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
So, it seems !empty($var) would be the equivalent to isset() && $var == true.
http://us2.php.net/empty
Try the empty function:
http://us2.php.net/empty
isset($a{0})
isset AND len is not 0 seems more reliable to me, if you run the following:
<?php
$a=$_REQUEST['a'];
if (isset($a{0})) { // Returns "It's 0!!" when test.php?a=0
//if (!empty($a)) { // Returns "It's empty!!" when test.php?a=0
echo 'It\'s '.$a;
} else { echo 'It\'s empty'; }
?>
$a = new stdClass;
$a->var_false = false;
$a->var_true = true;
if ($a->notSetVar ?? false) {
echo 'not_set';
}
if ($a->var_true ?? false) {
echo 'var_true';
}
if ($a->var_false ?? false) {
echo 'var_false';
}
This way:
if (($var ?? false) == true) {
}
I am amazed at all these answers. The correct answer is simply 'no, there is no single function for this'.
empty() tests for unset or false. So when you use !empty(), you test for NOT UNSET (set) and NOT FALSE. However, 'not false' is not the same as true. For example, the string 'carrots' is not false:
$var = 'carrots'; if (!empty($var)){print 1;} //prints 1
in fact your current solution also has this type problem
$var = 'carrots'; if (isset($var) && $var){print 1;} //prints 1
as does even this
$var = '1.03'; if (isset($var) && $var == true){print 1;} //prints 1
in fact... if you want to do as you described exactly, you need:
$var = 'carrots'; if (isset($var) && $var === true){print 1;} //Note the 3 Equals //doesn't print 1
I suppose the shortest valid way to test this case is :
if (#$var === true){ print 1;}
But suppressing errors for something like this is pretty awful practice.
Don't know if an exact one already exists, but you could easily write a custom function to handle this.
function isset_and_true($var) {
return (isset($var) && $var == true) ? true : false;
}
if (isset_and_true($a)) {
print "It's set!";
}
Check if the variable is set, and true. Ignore warning message
if(#!empty($foo))

Categories