Short if statement - php

I have found something weird...,
I have this piece of code at the end of my function:
return $class == 3?"red":$class==2?"orange":$class==1?"yellow":"";
Now, when $class == 2 this returns "yellow" and not "orange" like I expected.
Can someone explain this to me?

You need to use parentheses as ternary operators are left-associative in PHP. Associativity is how "operators of the same precedence are grouped in the absence of parentheses" - from Operator Associativity
$class == 3?"red":($class ==2?"orange":($class ==1?"yellow":""));

This is because it is treated like it was:
return (($class == 3?"red":$class==2)?"orange":$class==1)?"yellow":"";
So add brackets to force the right use:
return $class == 3?"red":($class==2?"orange":($class==1?"yellow":""));

I would never code it like that. I believe that when you are coding, you really want to see immediately what a piece of code is doing. This won't do that, this is just giving you headaches ;-)
Maybe change it to something clear:
switch($class) {
case 1:
return 'yellow';
case 2:
return 'orange';
case 3:
return 'red';
default:
return '';
}

use parentheses:
$class = 2;
echo $class == 3?"red":($class==2?"orange":($class==1?"yellow":""));
Output : orange

Related

php shorthand for or statement [duplicate]

Basically what I'm wondering if there is a way to shorten something like this:
if ($variable == "one" || $variable == "two" || $variable == "three")
in such a way that the variable can be tested against or compared with multiple values without repeating the variable and operator every time.
For example, something along the lines of this might help:
if ($variable == "one" or "two" or "three")
or anything that results in less typing.
in_array() is what I use
if (in_array($variable, array('one','two','three'))) {
Without the need of constructing an array:
if (strstr('onetwothree', $variable))
//or case-insensitive => stristr
Of course, technically, this will return true if variable is twothr, so adding "delimiters" might be handy:
if (stristr('one/two/three', $variable))//or comma's or somehting else
$variable = 'one';
// ofc you could put the whole list in the in_array()
$list = ['one','two','three'];
if(in_array($variable,$list)){
echo "yep";
} else {
echo "nope";
}
With switch case
switch($variable){
case 'one': case 'two': case 'three':
//do something amazing here
break;
default:
//throw new Exception("You are not worth it");
break;
}
Using preg_grep could be shorter and more flexible than using in_array:
if (preg_grep("/(one|two|three)/i", array($variable))) {
// ...
}
Because the optional i pattern modifier (insensitive) can match both upper and lower case letters.

Confusion about php code

Apologies if this is basic, but I'm learning php.
What does this snippet of code actually do? I've seen it in the source code for a plugin but can't quite figure out what's going on
$_POST['newName'] = $_POST['newName'] == "" ? "Dude" : $_POST['newName'];
Thanks.
This is a short version of if...else. This is a Ternary Logic.
$_POST['newName'] = $_POST['newName'] == "" ? "Dude" : $_POST['newName'];
if $_POST['newName'] == "" is true then "Dude" and else $_POST['newName'].
and both the value will be set in $_POST['newName'].
You can write this like this: [Full form]
if($_POST['newName'] == "")
$_POST['newName'] = "Dude";
The ? is also known as the ternary operator. It is called the ternary operator because it takes three operands - a condition, a result for true, and a result for false. If that sounds like an if statement to you, you are right on the money - the ternary operator is a shorthand (albeit very hard to read) way of doing if statements. Here's an example:
<?php
$agestr = ($age < 16) ? 'child' : 'adult';
?>
First there is a condition ($age < 16), then there is a question mark, and then a true result, a colon, and a false result. If $age is less than 16, $agestr will be set to 'child', otherwise it will be set to 'adult'. That one-liner ternary statement can be expressed in a normal if statement like this:
<?php
if ($age < 16) {
$agestr = 'child';
} else {
$agestr = 'adult';
}
?>
So, in essence, using the ternary operator allows you to compact five lines of code into one, at the expense of some readability.
Sometimes while coding, you might feel that writing an if(...){...}else{...} might feel like overkill for small amounts of code:
$result;
if (20>3)
{
$result = "bigger!";
}
else
{
$result = "smaller!";
}
So for this reason, a short hand notation was created where you would be able to express the exact same statement but without the need for such a big structure:
$result = (20>3) ? "bigger!" : "smaller!" ;
Whatever is between = and ? would then be the condition that is normally between the ( and ) of if(...). If that expression then equates to true, the value obtained by $result would be: "bigger!", and if it equated to false, the result would be: "smaller!".
As Frayne said, it is the shortened version of conditional statement. When we write it in full form, it becomes this:
<?php
if($_POST['newName'] == "") {
$_POST['newName'] = "Dude";
} else {
$_POST['newName'] = $_POST['newName'];
}

In PHP, is there a short way to compare a variable to multiple values?

Basically what I'm wondering if there is a way to shorten something like this:
if ($variable == "one" || $variable == "two" || $variable == "three")
in such a way that the variable can be tested against or compared with multiple values without repeating the variable and operator every time.
For example, something along the lines of this might help:
if ($variable == "one" or "two" or "three")
or anything that results in less typing.
in_array() is what I use
if (in_array($variable, array('one','two','three'))) {
Without the need of constructing an array:
if (strstr('onetwothree', $variable))
//or case-insensitive => stristr
Of course, technically, this will return true if variable is twothr, so adding "delimiters" might be handy:
if (stristr('one/two/three', $variable))//or comma's or somehting else
$variable = 'one';
// ofc you could put the whole list in the in_array()
$list = ['one','two','three'];
if(in_array($variable,$list)){
echo "yep";
} else {
echo "nope";
}
With switch case
switch($variable){
case 'one': case 'two': case 'three':
//do something amazing here
break;
default:
//throw new Exception("You are not worth it");
break;
}
Using preg_grep could be shorter and more flexible than using in_array:
if (preg_grep("/(one|two|three)/i", array($variable))) {
// ...
}
Because the optional i pattern modifier (insensitive) can match both upper and lower case letters.

Is it possible to have PHP if statement with all variables?

Simple question really. I have come across an issue with work where it would be ideal to store >= <= and == into a variable to spit out into certain if statements wherever the case may be.
$numb1 = 5
$numb2 = 10
$option = >=
if($numb1 $option $numb2)
You can't put a var for testing this in a control instruction.
This will return some : syntax error, unexpected T_VARIABLE
You could use some eval() to do it, but it's not advisable.
Perhap's you could make something different with the following :
$option=$_GET['option']; // or POST or something else...
$numb1 = 5;
$numb2 = 10;
switch($option) {
case ">=":
if($numb1 >= $numb2){//someting}
break;
case "<=":
if($numb1 <= $numb2){//someting}
break;
case "==":
if($numb1 == $numb2){//someting}
break;
default://something else if there is no $option
break;
}
Or with a function like the following
function testVar($numb1,$numb2,$option)
{
// Same switch
}
Not without using eval() which is generally considered a bad idea
Doing it directly like that, will only work using eval() - Using eval is not considered good practice. The main problem being that if the eval() statements takes in user input the user can inject php into your code. That's obviously bad. Refer this thread - When is eval evil in php?
What you'd be better off doing is created a series of switch statements for all the various operations such as 'greater than', 'less than', 'equals' and so forth...
The best thing to do for this is to make a function call or object wrapper, and then call the function to achieve the same result.
Example:
$func = '__my_eq_op_';
if ($func($numb1,$numb2)) {
// Do stuff
}
The operator functions are then...
function __my_eq_op($a,$b) {
return $a == $b;
}
function __my_gte_op($a,$b) {
return $a >= $b;
}
function __my_lte_op($a,$b) {
return $a <= $b;
}
For example. So you can really just break it down into using the functions instead.
For this:
if ($x == $y)
The parser sees 6 tokens...
1) KEYWORD IF:
2) LPAREN
3) VAR X
4) EQ
5) VAR Y
6) RPAREN
The parser uses these tokens to construct the AST for the IF conditional. Your thinking needs to move away from seeing the "==" as a variable. It's an operator!

PHP Shorten IF statement

So I have a variable we will say $string = 2;
if i want to check that variable for either 2 conditions I'd typically do
if($string == 2 || $string == "Hello world"):
Is there anyway to combine these two args into something shorter like
if($string(==2 || =="hello world")):
I've googled this but I cant come up with the right phrase to get back the answer I'm looking for so explaining it at this point is the easiest.
if (in_array($string, array(2, 'Hello world')))
See http://php.net/in_array.
A sick part of me wanted to answer this.
function f($a){
$args = func_get_args();
return in_array($a, array_slice($args, 1));
}
used like
if(f($str, 1, "hello world", 3, "etc")){
}
If variable have many states that can be processed in different ways, you can use switch statement:
switch($var)
{
case 1:
case 2:
//some action
break;
case 3:
break;
}

Categories