Since a year or so I had a function in all my projects called: ifNot().
This function is somehow a derivated from the ternary operator:
public function ifNot( $item, $ifNot )
{
if ( !$item ) {
return $ifNot
} else {
return $item;
}
}
// The var $foo twice
$var = ( $foo ) ? $foo : 'is empty or false =(';
// The var $foo once
$var = ifNot($foo, 'is empty or false =(');
In fact, Twig Template Engine use something like it:
{{ foo ? 'yes' : 'no' }}
{# as of Twig 1.12.0 #}
{{ foo ?: 'no' }} == {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} == {{ foo ? 'yes' : '' }}
The question is: There is a better/known approach for this function?
PS: SQL also has an IFNULL() =)
Your function is essentially equivalent to a variant of the conditional operator that was added in PHP 5.3:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
It may be a tiny bit faster to use the built-in approach if all your target environments are PHP 5.3 or greater, but I wouldn't really worry about it.
Yes, if your PHP is new enough (5.3.0 or newer). See the PHP documentation on the ternary operator
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
So while your code above is pretty awkward, there might be instances where you want a function version of this ternary operator (for example, to use as a callable - in those cases, you could just roll with a closure:
function($foo, $default) { return $foo ?: $default; }
$var = ifNot($foo, 'is empty or false =(');
is the same as:
$var = $foo?:'is empty or false =(';
In normal PHP (>= version 5.3) too. Your ifNot function is completely superfluous.
Related
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.)
This question already has answers here:
What are the PHP operators "?" and ":" called and what do they do?
(10 answers)
Closed 9 years ago.
what is the meaning of this line? Can any body help me? I have confusion on last 2 sign :''
why without this two sign browser make error? Thanks all.
isset($_POST['but'])? $_POST['but']:'';
U use the tenary comparison operator
A ternary operator have value for true and false
($contidition) ? true : false;
Please refer php documentation about ternary operator comparison operator
In case of:
isset( $_POST['but'] ) ? $_POST['but'] : ''
What it mean is, when $_POST['but'] exist, use it, otherwise use empty string
If u use php version > 5.3 u can use something like
isset($_POST['but']) ? : ''
It's just another way to write if/else statement.
For example:
$but = isset($_POST['but'])? $_POST['but']:'';
Would be the same as:
if(isset($_POST['but'])){
$but= $_POST['but'];
}else{
$but = '';
}
If $_POST request body contains but parameter - use it, overwise use empty string.
If you are misunderstood statement ? something : anything code - it's the Ternary Operator
It's nothing but the Ternary Operator
Explanation:
If your $_POST['but'] is set , then it will assign the same value to it , else it will set a ''
A clear example here
Well it's called an ternary operator.
Example:
$value = 5;
($value > 2) ? true : false; // returns true
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
(isset($_POST['but'])) ? $_POST['but']:'';
Here if your value $_POST['but'] is set then it will return $_POST['but'] else it will return ''.
In an online tutorial I have seen the following snippet of code:
$this->data = $data ?: \Input::all();
Is this a standard ternary operator? What would happen when $data evaluates to true?
Does the following code do the same thing as the original I posted?
$this->data = $data ? null : \Input::all();
It's a ternary operator, shortcut of
$this->data = $data? $data : \Input::all();
From http://php.net/manual/en/language.operators.comparison.php
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator.
Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
I am having issue with PHP's ternary operator, since PHP version 5.3 you are able to replace the shorthand ternary operator with an even shorter version
// Older version
$route = isset($test) ? $test : 'test is NOT set';
// Newer version as of 5.3
$route = isset($test) ?: 'test is NOT set';
Now on the newer version, if $test is not set. it works fine. However when it is set because of the isset() method, it is returning true or 1 instead of the value.
Do I have to use the older longer method to get $route to equal the value of $test instead of a boolean value of 1 ?
You have to use the longer version.
Quoting the docs:
Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
So the correct behaviour for your shorthand version is to return the result of evaluating isset($test). Not of $test as you want.
Starting from PHP 7, you can use the null coalescing operator:
$route = $test ?? 'test is NOT set';
which is equivalent to
$route = isset($test) ? $test : 'test is NOT set';
Here you can find some details:
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
what does this structure mean:
$var = isset($var_1) ? $var_1 : $var_2;
I came across it and of course with other values, not $va, $var_1 and $var_2.
thanks.
This is the ternary operator, and means the same as:
if (isset($var_1)) {
$var = $var_1;
}
else {
$var = $var_2;
}
The ternary operator provides a short-hand method of creating simple if/else statements.
It has some syntax errors, correctly:
$var = isset($var_1) ? $var_1 : $var_2;
This means:
if (isset($var_1))
{
$var = $var_1;
}
else
{
$var = $var_2;
}
That means:
if(isset($var_1))
$var = $var_1;
else
$var = $var_2;
It is short syntax for that.
just for your information from the php manual i copy pasted good things to know about ternary comparision operators
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
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:
Example #3 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.
?>