PHP shorthand if else condition issue - php

I can't understand what is wrong I am doing with this if else shorthand code
$item = '<li '. ($avatar_size > 50) ? .'style="overflow:hidden">';
I only want to check if condition true than add inline style else nothing.
Edit:
Of course in above statement it will remove > too when condition is false so I tried other statement but none of working. I am sure I must doing stupid mistake but can't figure it out.
$item = '<li '. ($avatar_size > 50) ? .'style="overflow:hidden"'.:. '' .'>';

There is no "shorthand if", ?: is an operator and it always must consist of ? and :. The best you can do with this is:
$item = '<li' . ($avatar_size > 50 ? ' style="overflow:hidden"' : null) . '>';

I have a late answer with more explanation, although the initial one is right.
About the ternary operator
$expression ? $value1 : $value2
The ternary operator works like a function, e.g. it returns a value.
Which value? That's where the first parameter comes into play. It is an expression that is evaluated either to true or false.
If it is true, the second parameter is returned as a value. If it is false, the third parameter is returned.
Since you are dealing with strings on the outside, the returned value will be used as a string. It is a very good idea to only return string values then and not confuse the reader of your code with returning NULL. It would be converted to an empty string nonetheless.
Shortcut ternary operator
$expression ?: $value
This one omits the second value for true, and returns $expression if this evaluates to true, or $value otherwise. This works great for checking whether a variable has been defined and set to a value (other than those that evaluate to false), and use a default value otherwise.
By reversing an expression is is possible to omit a parameter, but it is not possible to return an empty string or something else in your case.
$avatar_size <= 50 ?: ' style="overflow:hidden"'
This does not work because if the avatar size is below 50, a "true" would be returned and be used inside the string - which converts to "1".

Related

PHP Ternary Operators don't work as expected? [duplicate]

This question already has answers here:
Stacking Multiple Ternary Operators in PHP
(11 answers)
Closed 4 years ago.
I have a method that I'm checking if param is null, but if I use a ternary operator to make sure the false result isn't a string, I don't get the same expected result... I am a full stack .NET dev by day, but do some PHP free lance and this just stumped me...
$param = null;
// $active evaluates to true
$active = is_null($param) ? true : false;
// $active evaluates to false
$active = is_null($param) ? true : is_string($param)
? (strtolower($param) === 'true')
: true;
I have used nested ternary operators in C# and JavaScript what feels like countless times, but I don't know if I have ever tried in PHP... does PHP attempt to evaluate all nested ternary operations prior to expressing a result or is there something I'm missing here since from my understanding in this case, the ternary operator should be short circuited and evaluated to true in both circumstances.
The ternary operator is left associative unlike most other languages such as C#. The code:
$active = is_null($param)
? true
: is_string($param)
? (strtolower($param) === 'true')
: true;
is evaluated as follows:
$active = ((is_null($param) ? true : is_string($param))
? (strtolower($param) === 'true') : true);
You must explicitly add parenthesis to make sure ?: works the way it does in familiar languages:
$active = is_null($param)
? true
: (is_string($param)
? (strtolower($param) === 'true')
: true);
You need to wrap your second ternary condition with parenthesis (),
<?php
$param = null;
// $active evaluates to true
$active = is_null($param) ? true : false;
echo "Simple ternary result = $active".PHP_EOL;
// $active evaluates to true
$active = is_null($param) ? true : (is_string($param)? (strtolower($param) === 'true'): true);
echo "Nested ternary result = $active";
?>
Note:
It is recommended that you avoid "stacking" ternary expressions. PHP's
behaviour when using more than one ternary operator within a single
statement is non-obvious:
See Example #4 here at http://php.net/manual/en/language.operators.comparison.php
Example #4 Non-obvious Ternary Behaviour
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
DEMO: https://3v4l.org/gW8pk
This is a well-known problem with PHP. I doubt it will ever be fixed. Use parentheses, or if..else or switch statements, to get the behaviour you want.
(In technical terms, the ternary operator in PHP is "left associative", while that in every other language with this operator is "right associative". The latter is the more logical behaviour for this operator.)

PHP can't take more than one ternary operator?

Basically I have the following code:
However when I var_dump $isLoggedIn and $isset($_COOKIE['access_token']) both are false (so through the ! in the <?php?> it gets true) and the href should be connect.php... but it always is main.php?auto=true".autoooooo does not even exist (I just made it for testing) and href should actually be empty.
What am I doing wrong?
In php, the ternary operator (?:) associates left-to-right (unlike in C or perl where it associates right-to-left).
That means that it evaluates the first test ? value 1 : value 2, and then uses that result to determine which value of the second operator to use.
Your construct would work in C or perl, but in php, you need to add brackets around each subsequent ternary operator.
Also, for readability, I recommend you add quite a few newlines and indents in your code.
Use brackets for your 2nd clause:
$b1 = false;
$b2 = false;
echo $b1 ? 'b1 true' : ($b2 ? 'b2 true' : 'all false') ;
Output:
all false

how ordering makes a difference within an expression for an if statement

I have an array ...
$a= array(1,2,3,4);
if (expr)
{ echo "if";
}
else
{ echo 'else';
}
When expr is ( $a = '' || $a == 'false') , output is "if" ,
but when expr is ( $a == 'false' || $a = '' ) , output is "else"
Can anyone explain why & how ordering makes a difference ??
Edit : I understand that I am assigning '' to $a. That is not the problem. The real question is : What does the expression $a = '' return? And why does reversing the order of the 2 situations switch us from the IF section to the ELSE section?
AGAIN : I UNDERSTAND I AM ASSIGNING NOT COMPARING. PLEASE ANSWER THE QUESTION AS IS.
First, never use = as a comparison operator. It is an assignment operator.
The difference is that false (as a boolean) is not the same as 'false' as a string.
Certain expressions are type juggled by PHP to evaluate somewhat differently to how you would expect.
false==""
// TRUE.
false=="false"
// FALSE.
Additionally, when you try to compare numbers to strings, PHP will try to juggle the data so that a comparison will be performed. There is a lot to it (much more than I will post here) but you would do well to investigate type juggling and various operators. The docs are a great start for this. You should also have a read of the comparison operators which go into a lot of detail about how various comparisons will work (depending on whether you use == or === for example).
With $a = '' you are setting $a to an empty string. This is the same as:
$a = '';
if($a){
echo 'if';
}
The || operator checks if the first condition is true and if it is, it continues with the code in the brackets. In PHP, if $a is set to anything, it will return true. In the second case $a does not equal the string 'false' (you are not comparing it to a boolean false even!), so it executes the code in the else part.
And Fluffeh is not entirely correct. You can use the assignment operator in an if condition very effectively, you just have to be smart about it.
$a = '' is an assignment: you have, in error, used = in place of ==. Assignment is an expression which has the value of the thing your assigning.
A single equals sign = is the assignment opporator, so $a = '' is assigning an empty string to $a not checking if it is equal to.
In your 1st example you set the value of $a to an empty string, then check if it is false. An empty tring evalutes to false in php, so the conditional is true.
In your second example, you check if $a equals false 1st (when the value of $a is an array), so the conditional is false

What does the exclamation point mean in PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
Getting confused with empty, isset, !empty, !isset
In PHP what is the difference between:
if(!isset)
if(isset)
Same with if(!empty) and if(empty)?
What does the "!" character mean?
! is the logical negation or NOT operator. It reverses the sense of the logical test.
That is:
if(isset) makes something happen if isset is logical True.
if(!isset) makes something happen if isset is logical False.
More about operators (logical and other types) in the PHP documentation. Look up ! there to cement your understanding of what it does. While you're there, also look up the other logical operators:
&& logical AND
|| logical OR
xor logical EXCLUSIVE-OR
Which are also commonly used in logic statements.
The ! character is the logical "not" operator. It inverts the boolean meaning of the expression.
If you have an expression that evaluates to TRUE, prefixing it with ! causes it evaluate to FALSE and vice-versa.
$test = 'value';
var_dump(isset($test)); // TRUE
var_dump(!isset($test)); // FALSE
isset() returns TRUE if the given variable is defined in the current scope with a non-null value.
empty() returns TRUE if the given variable is not defined in the current scope, or if it is defined with a value that is considered "empty". These values are:
NULL // NULL value
0 // Integer/float zero
'' // Empty string
'0' // String '0'
FALSE // Boolean FALSE
array() // empty array
Depending PHP version, an object with no properties may also be considered empty.
The upshot of this is that isset() and empty() almost compliment each other (they return the opposite results) but not quite, as empty() performs an additional check on the value of the variable, isset() simply checks whether it is defined.
Consider the following example:
var_dump(isset($test)); // FALSE
var_dump(empty($test)); // TRUE
$test = '';
var_dump(isset($test)); // TRUE
var_dump(empty($test)); // TRUE
$test = 'value';
var_dump(isset($test)); // TRUE
var_dump(empty($test)); // FALSE
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
Edit:
here is a test case for you:
$p = false;
echo isset($p) ? '$p is setted : ' : '$p is not setted : ';
echo empty($p) ? '$p is empty' : '$p is not empty';
echo "<BR>";
$p is setted : $p is empty

Short-circuit evaluation via the AND operator in PHP

I'm trying to improve my coding ninja h4x skills, and I'm currently looking at different frameworks, and I have found sample code that's pretty hard to google.
I am looking at the FUEL framework used in a project.
The sample I don't understand is
$data and $this->template->set_global($data);
What is the and keyword doing in this line of code? It is used many places in the framework and it's the first that I have found that uses it.
This is a type of "short circuit evaluation". The and/&& implies that both sides of the comparison must evaluate to TRUE.
The item on the left of the and/&& is evaluated to TRUE/FALSE and if TRUE, the item on the right is executed and evaluated. If the left item is FALSE, execution halts and the right side isn't evaluated.
$data = FALSE;
// $this->template->set_global($data) doesn't get evaluated!
$data and $this->template->set_global($data);
$data = TRUE;
// $this->template->set_global($data) gets evaluated
$data and $this->template->set_global($data);
Note these don't have to be actual boolean TRUE/FALSE, but can also be truthy/falsy values according to PHP's evaluation rules. See the PHP boolean docs for more info on evaluation rules.
When you use logical operators, operands (the value on the left and the value on the right) are evaluated as boolean, so basically that code will do this, in a shorter way:
$o1 = (Bool)$data; // cast to bool
if($o1)
$o2 = (Bool)$this->template->set_global($data); // cast to bool
Edit:
Some additional information:
$a = 33;
isset($a) && print($a) || print("not set");
echo "<br>";
isset($a) AND print($a) OR print("not set");
echo "<br>";
Try to comment/decomment $a = 33;. This is the difference between && and AND, and between || and OR (print returns true that is casted to "1" when converted to string).
It is a valid statement and works like this:
If $data is valid (is not '', 0 or NULL) then run $this->template->set_global($data)
It's a quick way of saying:
if ($data)
{
$this->template->set_global($data);
}
Btw you can also use && instead of and
PHP supports both && and and for the logical AND operation, and they generally work identically, except and has a slightly lower operator precedence than &&: http://php.net/manual/en/language.operators.precedence.php
It's a boolean operator which means it takes two operands and returns a boolean value-- true or false. If both operands evaluate to true (anything but and empty string, zero or null in PHP) it will return true, otherwise the result will be false.
Here's PHP's official docs on the and operator: http://www.php.net/manual/en/language.operators.logical.php
<?php
$a = true and false; # FALSE
$b = true and 5; # TRUE
$c = '' and 0; # FALSE
$d = null and true; # FALSE
?>

Categories