Is !empty($a) ? $a : $b the same as $a ?: $b in PHP - php

I'm working on a new project and I've come upon the question if the ternary short hand operator the same as using the traditional ternary in combination with the empty() function?
For clarity purposes my question is if: $a ?: $b is the same as !empty($a) ? $a : $b ?

$a ?: $b is short-hand for $a ? $a : $b which is not quite the same as !empty($a) ? $a : $b
The difference between them requires careful reading of the definition of the empty pseudo-function:
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.
When you just use $a "in boolean context", as in if ( $a ) or $a ? $a : $b or $a ?: $b, its value will be converted to boolean. If the variable doesn't exist - a mistyped variable name, for instance - a Warning will be issued while retrieving that value.
The special power of the empty() pseudo-function is that it won't give you that Warning. The actual result will be the same - an unset variable is considered "equal to false" - but the two pieces of code aren't always interchangeable.

Related

What is the difference in the two not equal operator in php?

There are two not equal operator != and <>. Are they the same thing? Or are they slightly different from one another?
They are equal: http://php.net/manual/en/language.operators.comparison.php
$a != $b // Not equal TRUE if $a is not equal to $b after type juggling.
$a <> $b // Not equal TRUE if $a is not equal to $b after type juggling.
$a !== $b // Not identical TRUE if $a is not equal to $b, or they are not of the same type.
There is no difference. You can use both in MSSQL.
The MSSQL doc says:
!= functions the same as the <> (Not Equal To) comparison
operator.
But <> is defined in the ANSI 99 SQL standard and != is not. So not all DB engines may support it and if you want to generate portable code I recommend using <>.

PHP or shorthand for empty variable

$a = '';
$b = 1;
How to print $b if $a = '' using shorthand in PHP?
in javascript there is something like
a || b;
Ternary Operator
$a = '';
$b = 1;
echo $a ?: $b; // 1
Until $a is evaluated false, $b will be displayed. Remember that the following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
That means that if $a is "", 0, "0", null, false, array(), .. then $b will be displayed. See PHP type comparison tables.
If you want to display $b only when $a is an empty string, then you should uses strict comparison operators (===)
$a = '';
$b = 1;
echo $a === '' ? $b : ''; // 1
This is the shorthand for an IF/Else statement in PHP.
echo ($a != '' ? $a : $b)
If $a is not an empty string output (echo) $a otherwise output $b.
As others ahve said Turnary operator is handy for most senarios.
echo $a ?: $b;//b
But it is NOT shorthand for empty().
Ternary operator will issue notices if var/array keys/properties are not set.
echo $someArray['key that doesnt exist'] ?: $b;//Notice: Undefined index
echo $arrayThatDoesntExist['key-that-doesnt-exist'] ?: $b;//Notice: Undefined variable
empty() will take care of the additional checks for you and its recomended to just use it.
if (empty($arrayThatDoesntExist['key-that-doesnt-exist'])) echo $b;
You could technically just suppress the warning/notice with # and the ternary operator becomes a replacement for empty().
#echo $someArray['key that doesnt exist'] ?: $b;
#echo $arrayThatDoesntExist['key-that-doesnt-exist'] ?: $b;
But usually not recommended as supressing notices and warnings could lead you into trouble later on plus I think it may have some performance impact.

Javascript-like syntax in php [duplicate]

Javascript employs the conjunction and disjunction operators.
The left–operand is returned if it can be evaluated as: false, in the case of conjunction (a && b), or true, in the case of disjunction (a || b); otherwise the right–operand is returned.
Do equivalent operators exist in PHP?
PHP supports short-circuit evaluation, a little different from JavaScript's conjunction. We often see the example (even if it isn't good practice) of using short-circuit evaluation to test the result of a MySQL query in PHP:
// mysql_query() returns false, so the OR condition (die()) is executed.
$result = mysql_query("some faulty query") || die("Error");
Note that short-circuit evaluation works when in PHP when there is an expression to be evaluated on either side of the boolean operator, which would produce a return value. It then executes the right side only if the left side is false. This is different from JavaScript:
Simply doing:
$a || $b
would return a boolean value TRUE or FALSE if either is truthy or both are falsy. It would NOT return the value of $b if $a was falsy:
$a = FALSE;
$b = "I'm b";
echo $a || $b;
// Prints "1", not "I'm b"
So to answer the question, PHP will do a boolean comparison of the two values and return the result. It will not return the first truthy value of the two.
More idiomatically in PHP (if there is such a thing as idiomatic PHP) would be to use a ternary operation:
$c = $a ? $a : $b;
// PHP 5.3 and later supports
$c = $a ?: $b;
echo $a ?: $b;
// "I'm b"
Update for PHP 7
PHP 7 introduces the ?? null coalescing operator which can act as a closer approximation to conjunction. It's especially helpful because it doesn't require you to check isset() on the left operand's array keys.
$a = null;
$b = 123;
$c = $a ?? $b;
// $c is 123;

Does PHP support conjunction and disjunction natively?

Javascript employs the conjunction and disjunction operators.
The left–operand is returned if it can be evaluated as: false, in the case of conjunction (a && b), or true, in the case of disjunction (a || b); otherwise the right–operand is returned.
Do equivalent operators exist in PHP?
PHP supports short-circuit evaluation, a little different from JavaScript's conjunction. We often see the example (even if it isn't good practice) of using short-circuit evaluation to test the result of a MySQL query in PHP:
// mysql_query() returns false, so the OR condition (die()) is executed.
$result = mysql_query("some faulty query") || die("Error");
Note that short-circuit evaluation works when in PHP when there is an expression to be evaluated on either side of the boolean operator, which would produce a return value. It then executes the right side only if the left side is false. This is different from JavaScript:
Simply doing:
$a || $b
would return a boolean value TRUE or FALSE if either is truthy or both are falsy. It would NOT return the value of $b if $a was falsy:
$a = FALSE;
$b = "I'm b";
echo $a || $b;
// Prints "1", not "I'm b"
So to answer the question, PHP will do a boolean comparison of the two values and return the result. It will not return the first truthy value of the two.
More idiomatically in PHP (if there is such a thing as idiomatic PHP) would be to use a ternary operation:
$c = $a ? $a : $b;
// PHP 5.3 and later supports
$c = $a ?: $b;
echo $a ?: $b;
// "I'm b"
Update for PHP 7
PHP 7 introduces the ?? null coalescing operator which can act as a closer approximation to conjunction. It's especially helpful because it doesn't require you to check isset() on the left operand's array keys.
$a = null;
$b = 123;
$c = $a ?? $b;
// $c is 123;

PHP considers null is equal to zero

In PHP, ($myvariable==0)
When $myvariable is zero, the value of the expression is true; when $myvariable is null, the value of this expression is also true. How can I exclude the second case? I mean I want the expression to be true only when $myvariable is zero. Of course I can write
($myvariable != null && $myvariable == 0)
But is there other elegant way to do this?
$myvariable === 0
read more about comparison operators.
You hint at a deep question: when should an expression be true?
Below, I will explain why what you are doing isn't working and how to fix it.
In many languages null, 0, and the empty string ("") all evaluate to false, this can make if statements quite succinct and intuitive, but null, 0, and "" are also all of different types. How should they be compared?
This page tells us that if we have two variables being compared, then the variables are converted as follows (exiting the table at the first match)
Type of First Type of Second Then
null/string string Convert NULL to "", numerical/lexical comparison
bool/null anything Convert to bool, FALSE < TRUE
So you are comparing a null versus a number. Therefore, both the null and the number are converted to boolean. This page tells us that in such a conversion both null and 0 are considered FALSE.
Your expression now reads, false==false, which, of course, is true.
But not what you want.
This page provides a list of PHP's comparison operators.
Example Name Result
$a == $b Equal TRUE if $a equals $b after type juggling.
$a === $b Identical TRUE if $a equals $b, AND they are of the same type.
$a != $b Not equal TRUE if $a not equals $b after type juggling.
$a <> $b Not equal TRUE if $a not equals $b after type juggling.
$a !== $b Not identical TRUE if $a not equals $b, or they are not of the same type.
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than/equal TRUE if $a is less than or equal to $b.
$a >= $b Greater than/equal TRUE if $a is greater than or equal to $b.
The first comparator is the comparison you are using now. Note that it performs the conversions I mentioned earlier.
Using the second comparator will fix your problem. Since a null and a number are not of the same type, the === comparison will return false, rather than performing type conversion as the == operator would.
Hope this helps.
To identify as null or zero by:
is_int($var) if a variable is a number or a numeric string. To identify Zero, use is_numeric($var) is also the solution or use $var === 0
is_null($var) if a variable is NULL
Try ($myvariable === 0) which will not perform type coercion.
Use the php function is_null( ) function along with the === operator. !== also works the way you'd expect.
The second solution wouldn't work either. The === operator is the solution to your problem.
If your zero could be a string, you should also considere checking the "zero string"
($myvariable === 0 || $myvariable === '0')
I hade faced a similar issue in one of my projects, with a minor difference that I was also using the values ZERO as a valid value for my condition. here's how I solved it using simple logic to separate NULL from zero and other values.
if (gettype($company_id) === 'NULL') {
$company = Company::where('id', Auth::user()->company_id)->first();
} else {
$company = Company::where('id', $company_id)->first();
}
$myvariable===0
$a === $b
Identical TRUE if $a is equal to $b, and they are of the same type
There's an is_null function, but this will just replace your $myvariable!=null
For my case i found this soulution and it works for me :
if ($myvariable === NULL) {
codehere...
}

Categories