(and Notice: Undefined variable: x)
This post was published 14 May, 2018 (and was last revised 06 Jun, 2021 ) by Daniyal Hamid . Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post .
You probably already know some comparison operators in PHP. Things like the ternary ?: , the null coalescing ?? and the spaceship <=> operators. But do you really know how they work? Understanding these operators makes you use them more, resulting in a cleaner codebase.
Before looking at each operator in depth, here's a summary of what each of them does:
The ternary operator is a shorthand for the if {} else {} structure. Instead of writing this:
You can write this:
If this $condition evaluates to true , the lefthand operand will be assigned to $result . If the condition evaluates to false , the righthand will be used.
Interesting fact: the name ternary operator actually means "an operator which acts on three operands". An operand is the term used to denote the parts needed by an expression. The ternary operator is the only operator in PHP which requires three operands: the condition, the true and the false result. Similarly, there are also binary and unary operators. You can read more about it here .
Back to ternary operators: do you know which expressions evaluate to true , and which don't? Take a look at the boolean column of this table .
The ternary operator will use its lefthand operand when the condition evaluates to true . This could be a string, an integer, a boolean etc. The righthand operand will be used for so called "falsy values".
Examples would be 0 or '0' , an empty array or string, null , an undefined or unassigned variable, and of course false itself. All these values will make the ternary operator use its righthand operand.
Noticed a tpyo? You can submit a PR to fix it. If you want to stay up to date about what's happening on this blog, you can subscribe to my mailing list : send an email to [email protected] , and I'll add you to the list.
Since PHP 5.3, it's possible to leave out the lefthand operand, allowing for even shorter expressions:
In this case, the value of $result will be the value of $initial , unless $initial evaluates to false , in which case the string 'default' is used.
You could write this expression the same way using the normal ternary operator:
Ironically, by leaving out the second operand of the ternary operator, it actually becomes a binary operator .
The following, even though it seems logical; doesn't work in PHP:
The reason because is that the ternary operator in PHP is left-associative, and thus parsed in a very strange way. The above example would always evaluate the $elseCondition part first, so even when $firstCondition would be true , you'd never see its output.
I believe the right thing to do is to avoid nested ternary operators altogether. You can read more about this strange behaviour in this Stack Overflow answer .
Furthermore, as PHP 7.4, the use of chained ternaries without brackets is deprecated .
New in PHP 8.3
Did you take a look at the types comparison table earlier? The null coalescing operator is available since PHP 7.0. It similar to the ternary operator, but will behave like isset on the lefthand operand instead of just using its boolean value. This makes this operator especially useful for arrays and assigning defaults when a variable is not set.
The null coalescing operator takes two operands, making it a binary operator. "Coalescing" by the way, means "coming together to form one mass or whole". It will take two operands, and decide which of those to use based on the value of the lefthand operand.
This operator is especially useful in combination with arrays, because of its acts like isset . This means you can quickly check for the existence of keys, even nested keys, without writing verbose expressions.
The first example could also be written using a ternary operator:
Note that it's impossible to use the shorthand ternary operator when checking the existence of array keys. It will either trigger an error or return a boolean, instead of the real lefthand operand's value.
The null coalescing operator can easily be chained:
It's possible to use the null coalescing operator on nested object properties, even when a property in the chain is null .
In PHP 7,4, we can expect an even shorter syntax called the "null coalescing assignment operator" .
In this example, $parameters['property'] will be set to 'default' , unless it is set in the array passed to the function. This would be equivalent to the following, using the current null coalescing operator:
The spaceship operator, while having quite a peculiar name, can be very useful. It's an operator used for comparison. It will always return one of three values: 0 , -1 or 1 .
0 will be returned when both operands are equals, 1 when the left operand is larger, and -1 when the right operand is larger. Let's take a look at a simple example:
This simple example isn't all that exiting, right? However, the spaceship operator can compare a lot more than simple values!
Strangely enough, when comparing letter casing, the lowercase letter is considered the highest. There's a simple explanation though. String comparison is done by comparing character per character. As soon as a character differs, their ASCII value is compared. Because lowercase letters come after uppercase ones in the ASCII table, they have a higher value.
The spaceship operator can almost compare anything, even objects. The way objects are compared is based on the kind of object. Built-in PHP classes can define their own comparison, while userland objects are compared based on their attributes and values.
When would you want to compare objects you ask? Well, there's actually a very obvious example: dates.
Of course, comparing dates is just one example, but a very useful one nevertheless.
One great use for this operator, is to sort arrays. There are quite a few ways to sort an array in PHP, and some of these methods allow a user defined sort function. This function has to compare two elements, and return 1 , 0 , or -1 based on their position.
An excellent use case for the spaceship operator!
To sort descending, you can simply invert the comparison result:
Hi there, thanks for reading! I hope this blog post helped you! If you'd like to contact me, you can do so on Twitter or via e-mail . I always love to chat!
Supunkavinda
Online IT courses
In the domain of PHP programming, employing succinct conditional operators not only elevates code readability but also enhances its conciseness. This article delves into two specialized shorthand conditional operators in PHP: the Ternary Operator and the Null Coalescing Operator. Let’s explore the intricacies of PHP Ternary Shorthand to facilitate efficient and succinct coding.
The Ternary Operator provides a concise approach to execute conditional checks in PHP. Its syntax is structured as follows:
If the condition is true, the result of the “on true” expression is returned; otherwise, the result of the “on false” expression is returned. Since PHP 5.3, you can omit the “on true” expression using `(condition) ?: (on false)`, returning the result of the condition if true and the “on false” expression if false.
It is advisable to utilize the ternary operator for straightforward conditions and avoid nesting for enhanced code clarity.
Tip: The isset() function checks if variables are set and not null.
Explore the essentials of PHP data types , including Booleans and Integers
Introduced in PHP 7, the Null Coalescing Operator is a valuable feature for assigning default values to variables, streamlining code, and enhancing readability.
Nesting null coalescing operator, taking ternary shorthand further.
The Ternary Shorthand in PHP proves invaluable for handling various scenarios efficiently. Let’s explore some additional use cases and tips to maximize its potential.
Beyond simple greetings, the Ternary Operator can be employed to enhance output conditions based on dynamic variables. Consider the following:
This concise code adjusts the weather status based on the temperature, providing a straightforward output.
When working with user input, especially in form validation, the Ternary Operator can streamline the process:
Here, the operator checks whether the user input is empty or not, facilitating quick validation.
Ternary Shorthand Tips:
For instance:
This example evaluates if the length of the text is greater than 10 characters.
The Null Coalescing Operator in PHP 7 introduces enhanced flexibility in handling default values. Let’s explore further applications and considerations.
In configuration settings, the Null Coalescing Operator simplifies the process of assigning default values:
This ensures a default value is present if the configuration key is not explicitly defined.
The Null Coalescing Operator’s ability to chain provides a concise way to select the first defined value:
In this example, it picks the first non-null choice, offering flexibility in handling various scenarios.
Default to Empty Arrays: When dealing with arrays, use the null coalescing operator to default to an empty array if the key is not present:
This ensures smooth array handling.
While the null coalescing operator is versatile, be mindful of data types. Ensure the default value matches the expected type for consistent behavior.
Mastering the Ternary Shorthand and Null Coalescing Operator in PHP opens doors to efficient, readable, and flexible code. By understanding their nuances and exploring diverse applications, developers can navigate complex scenarios with elegance. Embrace these tools judiciously, applying them where their succinctness enhances the overall codebase.
Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables , as they show examples of various type related comparisons.
Example | Name | Result |
---|---|---|
$a == $b | Equal | if is equal to after type juggling. |
$a === $b | Identical | if is equal to , and they are of the same type. |
$a != $b | Not equal | if is not equal to after type juggling. |
$a <> $b | Not equal | if is not equal to after type juggling. |
$a !== $b | Not identical | if is not equal to , or they are not of the same type. |
$a < $b | Less than | if is strictly less than . |
$a > $b | Greater than | if is strictly greater than . |
$a <= $b | Less than or equal to | if is less than or equal to . |
$a >= $b | Greater than or equal to | if is greater than or equal to . |
$a <=> $b | Spaceship | An less than, equal to, or greater than zero when is less than, equal to, or greater than , respectively. |
If both operands are numeric strings , or one operand is a number and the other one is a numeric string , then the comparison is done numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
Output of the above example in PHP 7:
Output of the above example in PHP 8:
<?php // Integers echo 1 <=> 1 ; // 0 echo 1 <=> 2 ; // -1 echo 2 <=> 1 ; // 1 // Floats echo 1.5 <=> 1.5 ; // 0 echo 1.5 <=> 2.5 ; // -1 echo 2.5 <=> 1.5 ; // 1 // Strings echo "a" <=> "a" ; // 0 echo "a" <=> "b" ; // -1 echo "b" <=> "a" ; // 1 echo "a" <=> "aa" ; // -1 echo "zz" <=> "aa" ; // 1 // Arrays echo [] <=> []; // 0 echo [ 1 , 2 , 3 ] <=> [ 1 , 2 , 3 ]; // 0 echo [ 1 , 2 , 3 ] <=> []; // 1 echo [ 1 , 2 , 3 ] <=> [ 1 , 2 , 1 ]; // 1 echo [ 1 , 2 , 3 ] <=> [ 1 , 2 , 4 ]; // -1 // Objects $a = (object) [ "a" => "b" ]; $b = (object) [ "a" => "b" ]; echo $a <=> $b ; // 0 $a = (object) [ "a" => "b" ]; $b = (object) [ "a" => "c" ]; echo $a <=> $b ; // -1 $a = (object) [ "a" => "c" ]; $b = (object) [ "a" => "b" ]; echo $a <=> $b ; // 1 // not only values are compared; keys must match $a = (object) [ "a" => "b" ]; $b = (object) [ "b" => "b" ]; echo $a <=> $b ; // 1 ?>
For various types, comparison is done according to the following table (in order).
Type of Operand 1 | Type of Operand 2 | Result |
---|---|---|
or | Convert to "", numerical or lexical comparison | |
or | anything | Convert both sides to , < |
Built-in classes can define its own comparison, different classes are incomparable, same class see | ||
, , or | , , or | Translate strings and resources to numbers, usual math |
Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are incomparable, otherwise - compare value by value (see following example) | ||
anything | is always greater | |
anything | is always greater |
Example #1 Boolean/null comparison
Example #2 Transcription of standard array comparison
Because of the way float s are represented internally, you should not test two float s for equality.
See the documentation for float for more information.
Note : Be aware that PHP's type juggling is not always obvious when comparing values of different types, particularly comparing int s to bool s or int s to string s. It is therefore generally advisable to use === and !== comparisons rather than == and != in most cases.
While identity comparison ( === and !== ) can be applied to arbitrary values, the other comparison operators should only be applied to comparable values. The result of comparing incomparable values is undefined, and should not be relied upon.
Example #3 Assigning a default value
It is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 evaluates to the result of expr1 if expr1 evaluates to true , and expr3 otherwise. expr1 is only evaluated once in this case.
Note : Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. 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.
Note : It is recommended to avoid "stacking" ternary expressions. PHP's behaviour when using more than one unparenthesized ternary operator within a single expression is non-obvious compared to other languages. Indeed prior to PHP 8.0.0, ternary expressions were evaluated left-associative, instead of right-associative like most other programming languages. Relying on left-associativity is deprecated as of PHP 7.4.0. As of PHP 8.0.0, the ternary operator is non-associative. 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' prior to PHP 8.0.0 // this is because ternary expressions are left-associative // the following is a more obvious version of the same code as above echo (( true ? 'true' : false ) ? 't' : 'f' ); // here, one 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. ?>
Note : Chaining of short-ternaries ( ?: ), however, is stable and behaves reasonably. It will evaluate to the first argument that evaluates to a non-falsy value. Note that undefined values will still raise a warning. Example #5 Short-ternary chaining <?php echo 0 ?: 1 ?: 2 ?: 3 , PHP_EOL ; //1 echo 0 ?: 0 ?: 2 ?: 3 , PHP_EOL ; //2 echo 0 ?: 0 ?: 0 ?: 3 , PHP_EOL ; //3 ?>
Example #6 Assigning a default value
In particular, this operator does not emit a notice or warning if the left-hand side value does not exist, just like isset() . This is especially useful on array keys.
Note : Please note that the null coalescing operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $foo ?? $bar; in a return-by-reference function will therefore not work and a warning is issued.
Note : The null coalescing operator has low precedence. That means if mixing it with other operators (such as string concatenation or arithmetic operators) parentheses will likely be required. <?php // Raises a warning that $name is undefined. print 'Mr. ' . $name ?? 'Anonymous' ; // Prints "Mr. Anonymous" print 'Mr. ' . ( $name ?? 'Anonymous' ); ?>
Note : Please note that the null coalescing operator allows for simple nesting: Example #7 Nesting null coalescing operator <?php $foo = null ; $bar = null ; $baz = 1 ; $qux = 2 ; echo $foo ?? $bar ?? $baz ?? $qux ; // outputs 1 ?>
User contributed notes 14 notes.
Home » PHP Tutorial » PHP Assignment Operators
Summary : in this tutorial, you will learn about the most commonly used PHP assignment operators.
PHP uses the = to represent the assignment operator. The following shows the syntax of the assignment operator:
On the left side of the assignment operator ( = ) is a variable to which you want to assign a value. And on the right side of the assignment operator ( = ) is a value or an expression.
When evaluating the assignment operator ( = ), PHP evaluates the expression on the right side first and assigns the result to the variable on the left side. For example:
In this example, we assigned 10 to $x, 20 to $y, and the sum of $x and $y to $total.
The assignment expression returns a value assigned, which is the result of the expression in this case:
It means that you can use multiple assignment operators in a single statement like this:
In this case, PHP evaluates the right-most expression first:
The variable $y is 20 .
The assignment expression $y = 20 returns 20 so PHP assigns 20 to $x . After the assignments, both $x and $y equal 20.
Sometimes, you want to increase a variable by a specific value. For example:
How it works.
After the assignments, the value of $counter is 2 .
PHP provides the arithmetic assignment operator += that can do the same but with a shorter code. For example:
The expression $counter += 1 is equivalent to the expression $counter = $counter + 1 .
Besides the += operator, PHP provides other arithmetic assignment operators. The following table illustrates all the arithmetic assignment operators:
Operator | Example | Equivalent | Operation |
---|---|---|---|
+= | $x += $y | $x = $x + $y | Addition |
-= | $x -= $y | $x = $x – $y | Subtraction |
*= | $x *= $y | $x = $x * $y | Multiplication |
/= | $x /= $y | $x = $x / $y | Division |
%= | $x %= $y | $x = $x % $y | Modulus |
**= | $z **= $y | $x = $x ** $y | Exponentiation |
PHP uses the concatenation operator (.) to concatenate two strings. For example:
By using the concatenation assignment operator you can concatenate two strings and assigns the result string to a variable. For example:
PHP supports various forms of ternary and coalescing operators. This is a quick post to catch-up to all ternary and coalescing operators supports in PHP.
Ternary operator is a short form for an if/else block that executes exactly one expression each.
The if/else block above is quite verbose and consumes more space for a simple expression. With the ternary operator, you can optimize this:
Its syntax is follows:
PHP will execute condition condition, and if it evaluates to "true-ish" value (same semantics as an if() condition), value from expression-if-true is used. If condition evaluates to false, value from expression-if-false will be used.
An ideal use case of Ternary operator would be assignments that can have two values.
From PHP 8.0+, you can also throw an exception from a Ternary operator .
Certain Ternary operator expressions can be simplified further. Consider the following Ternary expression:
If the conditional expression is the same as the true-expression, it is possible to reduce this further:
If load_user() function returns a false-ish value, $user will be assigned false . Otherwise, the return value of load_user() will be assigned.
Its syntax is:
The cond condition will be evaluated as if it's in an if() block, and the return value will be assigned to result if it is a truthy value. If it's a false-ish value (such as 0 , "0" , false , null , [] , etc), the expression-if-false expression will be evaluated, and its return value will be assigned to result .
Null Coalescing Operator provides a shorthand for isset() calls. It is often used to reduce excessive isset() calls. Null Coalescing operator calls isset() on the conditional expression, and the value will be returned.
If $_GET['value'] is set (which behaves exactly the way isset() does), $_GET['value'] value will be assigned to $result . If it is not set, or null , foo will be assigned to $result .
PHP calls isset(variable) , and variable will be assigned to result if variable is set. If it is not set, expression will be evaluated, and its value will be assigned to result .
Null Coalescing operator can be be further reduced in PHP 7.4, with Null Coalescing Assignment operator .
Be mindful when you chain ternary/coalescing operators. It is now required to use braces to make the intent clear if you absolutely have to use ternary/coalescing operators.
Null Coalescing Assignment operator is relatively new in PHP (added in PHP 7.4), so you code might not work in older PHP versions if you decide to use that operator.
These operators are syntax sugar only, and do not provide any meaningful performance difference compared to good ol' if/else blocks. When the intent is not clear, it is recommended to go with if/else blocks although they make the code slightly verbose
You will receive an email on last Wednesday of every month and on major PHP releases with new articles related to PHP, upcoming changes, new features and what's changing in the language. No marketing emails, no selling of your contacts, no click-tracking, and one-click instant unsubscribe from any email you receive.
An essential part of programming is evaluating conditions using if/else and switch/case statements. If / Else statements are easy to code and global to all languages. If / Else statements are great but they can be too long.
I preach a lot about using shorthand CSS and using MooTools to make JavaScript relatively shorthand, so I look towards PHP to do the same. If/Else statements aren't optimal (or necessary) in all situations. Enter ternary operators.
Ternary operator logic is the process of using "(condition) ? (true return value) : (false return value)" statements to shorten your if/else structures.
What are the advantages of ternary logic.
There are some valuable advantages to using this type of logic:
Here are a few tips for when using "?:" logic:
Here are a couple more uses of ternary operators, ranging from simple to advanced:
To learn more about ternary operators and usage, visit PHP.net Comparison Operators .
I spent a few months experimenting with different approaches for writing simple, elegant and maintainable media queries with Sass. Each solution had something that I really liked, but I couldn't find one that covered everything I needed to do, so I ventured into creating my...
Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...
Google Plus provides loads of inspiration for front-end developers, especially when it comes to the CSS and JavaScript wonders they create. Last year I duplicated their incredible PhotoStack effect with both MooTools and pure CSS; this time I'm going to duplicate...
One thing I love about love about Safari on the iPhone is that Safari provides a darkened background effect when you click a link. It's the most subtle of details but just enforces than an action is taking place. So why not implement that...
Nice job clarifying this! I keep forgetting the exact syntax for some reason…
Your second echo example in the more examples is missing the first ‘e’ in the code.
Nice article. I use this all the time. Often if/else statements get way too complicated. I love to shorten code and the (?:) operator helps a lot. It’s even a lot better when you can shorten it more than a (?:) can do: Yesterday I saw this excample in a high-end PHP OOP book:
if ($condition){ return true; } else { return false }
It’s a lot easier to just use:
return condition;
Mind you, the if-statement you supplied checks if $condition is NOT false, everything else will pass, which might not always be ideal.
You can always write:
To be sure that you return boolean.
I’ve been looking for a good explanation of this, thank you.
Now I’m off to scour my code for opportunities to practice.
ohh wow man, i really needed this thanks for sharing that with such nice explanation
thanks again
If you have some experience with Javascript I would say that it is similar to:
var test = result || error; //Javascript $test = $result ?: $error; //PHP
In which it would return “result” value if it is not empty [1]. Otherwise it will return “error” value.
I hope I was clear.
[1] : For empty values see: http://www.php.net/manual/en/function.empty.php
/* echo, inline */ echo ‘Based on your score, you are a ‘,($score > 10 ? ‘genius’ : ‘nobody’); //harsh!
I think you may a typo with the ‘,’ instead of a ‘.’
The comma is not a typo. Echo can take multiple strings as arguments. :)
http://php.net/manual/en/function.echo.php
These are nice shorthands, but be warned, it will make your code unreadable and less understandable.
What Stjepano says
If you code for longer, you start to let go of niftyness and look more towards readability. Using ternary operator wrong, indicates to me a lack of experience and/or youthful enthusiasm.
If you use them: – never nest ternary operators – Store the result in a variable which is named after the result (Eg. $geniusStatusLabel = ($iq>120)?'genius':'below genius' ) and use the variable later. – Be consistent in preferred value (if applicable). Eg. the following looks ackward $var = !isset($_POST['var'])?null:$_POST['var']
What is wrong with this code, I keep receiving an error. Creating a sticky form and I am using a simple if (submit) then ( $_POST['value'] )
I only need the if part of the if/else.
Thanks for any help
For people that might see this when searching..
$_POST['value'] should be $_POST['catBlurb']
Hey Dave! I don’t use ternary very often, but is really nice in spots where things need to be tidy.
I have a bit of a word of advice here on the use of ternary and collaboration. Dave addresses that in his points above, “Tips for Using Ternary Operators”.
As a rule I use ternary only if the If/Else is a ‘single line of code’ <— Yes this is variable depending on screen size. Just don't go overboard when working collaboratively or if there is a chance some-one else will inherit the code.
Great article. In the first example, I think it’s the same thing as doing : $var_is_greater_than_two = ($var > 2); Right ?
Technically yes, but the ternary operator lets you output whatever you want (i.e. a string “IT’S BIGGER!”, and not just true or false like in your example. This demonstrates how much more flexibility you get when using the ternary operator. :)
Excellent… would be. But parts of the page does not display under Opera/NetBSD. Please fix it. TIA
Good article, I’m glad some poeple cover this. One thing should be mentioned though – this should definitely not be used heavily. Embedded ternary operators, and nested ternary operators are a developer’s worst nightmare – it creates unnecessarily unreadable code that is difficult to maintain. Sometimes more code is better! :)
i’am looking for this thing , thx for your explanation bro.
Thank you for this explanation. I have a background in Java so coming to PHP I see many similar coding between the two. This is one of them. But I wanted to make sure its the same in both and found you via Google when searching.
“Makes maintaining code quicker, easier” – I’d say that it’s quote contrary. It makes it more difficult and obscure, not easier (these statements are by far easier to accidentally skip or misunderstand while analysing the code than regular ifs).
Thanks, David! You’re doing great job revealing PHP mysteries.
so, can i shorten this if else using ternary?
You should use switch/case http://php.net/manual/en/control-structures.switch.php
wish we had a syntax to test something and assign it to l_value if the test was successfull like y = x > 4 ?; means y = x if x > 4
y = x > 4 ? : z; means y= x if x > 4 else y = z would be a shorthand for y= x > 4 ? x : z
Note usually when we test a condition on a variable we want to assign the same value as above
then we could have
y = x > 4 ? w : z; means y = w if x > 4 else y = z
Thanks.. This was just what I was looking for!
Thanks… That is what i am looking for, sample usage attracts me!
Thanks bro, now I understand :)
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. http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
You should show an example e.g.
echo $username ?: ‘unknown’; // same as echo $username ? $username : ‘unknown’;
Thanks for clarifying this only works from PHP 5.3+, I was getting nuts trying to figure it out why it wasn’t working.
Unlike (literally!) every other language with a similar operator, ?: is left associative. So this:
Will output: horse
Not all languages do things the same way. So you should never expect the same behavior in any of them. Though be pleasantly surprised is they are. For all other cases adapt your code accordingly.
Which is also usable in PHP in the same way. And both output the same result. This way if you want your code to be decently portable between languages, if that's a concern. Write it in a way that works either for both or decently for both.
Wow! I did not know that you don’t have to put a value after the question mark i.e. that you can do this:
Can I also do this:
Or will that throw an error?
The ternary operator IS NOT the same as if/else; a ternary operator assures that a variable is given an assignment.
compare that to:
I did want to add that in PHP ternary does not always make code shorter than a if/else. Given that you can code in similar if/else blocks to that of ternary. Many people are so hooked on the typical logic that if/else requires specifically if and else and brackets { }. Then when you do deeply nested ternary you then use ( ). Though with deeply nested if/else you can forgo the brackets, you can not with ternary. A deeply nested if/else simply understands the flow of logic without them. IE so many )))))))))); at the end of a deeply nested ternary. Which you can forgo in a deeply nested if/else, which the blow structure can also be a part of.
Don’t do stupid things with PHP. Make your code human readable. i.e.
Thanks for introducing me to this concept. It makes the code a lot shorter and once you are used to it even easier to read. I use this quite often now for example in this context:
could actually be just:
and its much clearer…
Just my two cents.
Technically yes, but the ternary operator lets you output whatever you want (i.e. a string “IT’S BIGGER!”, and not just true or false like in your example. This demonstrates how much more flexibility you get when using the ternary operator. :)
Very clean and nice, thanks :-)
I linked to it in my first post http://davidwalsh.name/php-shorthand-if-else-ternary-operators#comment-78632
> 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.
The ternary operator shouldn’t differ in performance from a well-written equivalent if/else statement… The only potential benefit to ternary operators over plain if statements in my view is their ability to be used for initializations
You mention in your article a list of advantages but you fail to mention the disadvantages. Also, one would argue that some of the claimed advatages are questionable. For example it can make maintaining the code slower and harder instead of quicker and easier if the expression in the ternary operator is not completely basic.
Some other disadvantages. – Code is more prone to cause a conflicts when merging changes from different developers. – It makes debugging more difficult since you can not place breakpoints on each of the sub expressions. – It can get very difficult to read – It can lead to long lines of code
Another disadvantage for the operators ternary is more slow than the operator traditional, or not?
For example:
http://fabien.potencier.org/the-php-ternary-operator-fast-or-not.html
What do you mean by “Job security”?
return !!$condition
Good One “Job Security”!
For flexibility yes, for readability no. It looks like a mess at first glance if overused and I’m not a fan of it unless i need to use it.
In php, does the
evaluate all of the expressions before assigning the expression-2 or the expression-2 result to the value based on the expression-1, without or without short-circuiting? If so, then care must be taken to ensure that both expression-2 and expression-3 (and, of coarse, expression-1) are valid, which makes using the ternary operator somewhat more complicated than it might at first seem, such as when handling optional parameters.
Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!
Are you tired of typing out long lines of code? Do you wish there was a faster way to write code without sacrificing readability? Look no further than shorthand programming! Shorthand allows you to write code in a more abbreviated syntax, saving your time and effort.
But what exactly is shorthand programming and how can you use it to your advantage? In programming, shorthand refers to a way of writing code using abbreviated syntax.
Hope by now, you would have got some clarity about shorthand programming. In this blog, we are going to particularly look into the concept of Shorthand comparisons in PHP using an abbreviated syntax, saving your time and effort.
Lets get started!
Shorthand comparison, also known as the ternary operator, is a shorthand way of writing an if-else statement in PHP. It is used to assign a value to a variable based on a condition.
You may be familiar with some of the comparison operators in PHP, such as the ternary operator ?: , the null coalescing operator ?? , and the spaceship operator <=> . By understanding these operators in more detail, you can use them more effectively and write more concise and readable code.
The null coalescing operator is a shorthand way of checking if a variable is null and returning a default value if it is. The null coalescing operator is denoted by ?? . The double question marks were chosen to avoid conflicts with other operators and to make the operator easy to remember and type. This is available in PHP starting from version 7.0.
In this syntax:
Let us look into some examples to understand the concept of null coalescing better.
Example: In the below example, we use isset() to check if the $_POST variables are set, and then assign the appropriate value to the $firstName and $lastName variables.
Here is an equivalent example code that achieves the same result with using the null coalescing operator.
In this example, we use the null coalescing operator to assign a default value of Unknown to the $firstName and $lastName variables if they are not set in the $_POST super global array.
In PHP, the Null coalescing operator ?? can be used with arrays to provide a shorthand way of assigning a default value to a variable if the array element being accessed is null.
Example: Assigning a default value to an array element.
In this example, an array is created with four elements, including two null values. This code assigns the value of the first element of the array to the variable $value , but if the value of the first element is null , it assigns the default value of default to the variable instead. This is achieved using the null coalescing operator ?? .
In this case, since the value of the first element of the array is null, the null coalescing operator assigns the value default to the variable $value .
Example: Assigning a default value to an array if it is null.
This code assigns the value of $array to the variable $value , but if the value of $array is null , it assigns the default value of [" default "] to the variable instead. This is achieved using the null coalescing operator ?? .
In this case, since the value of $array is null , the null coalescing operator assigns the default value of [" default "] to the variable $value .
Null coalesce chaining allows you to chain multiple null coalescing operations together, so that if any one of them returns a non-null value, the entire expression will evaluate to that value.
Here is an example of using null coalesce chaining:
The code defines an associative array $userData which represents the user data. The array has three key-value pairs. The name key has a non-null value, while the email and phone keys have null values. The code uses null coalesce chaining to set the values of three variables.
$displayName is set to the value of $userData['displayName' ] , or if that value is null, the value of $userData['name'] , or if that value is also null, the string Guest . The null coalesce operator ( ?? ) allows the code to check each value in turn until a non-null value is found. In this case, since $userData['name'] is non-null, it is used as the value of $displayName .
$userEmail is set to the value of $userData['email'] , or if that value is null, the string No email provided . This line is straightforward: if the email is not provided, the string No email provided is used as a default value.
$userPhone is set to the value of $userData['phone'] , or if that value is null, the string 'No phone number provided' . This line is similar to the previous line, but for the phone number.
And finally, the code uses echo statements to output the values of each variable.
Nested coalescing is a technique in PHP that allows you to check for nested null values and return a default value if any of the values are null. This technique involves using multiple null coalescing operators ( ?? ) to check each nested value in turn until a non-null value is found.
In this example, the $userData array contains an inner array under the address key. The street key in the inner array has a null value, while the city and state keys have non-null values.
The code uses nested null coalescing operators to check each nested value in turn. The first line checks the value of $userData['address']['street'] . Since this value is null, the default value of ' Unknown ' is used instead.
The second and third lines check the values of $userData['address']['city'] and $userData['address']['state'] , respectively. Since these values are non-null, they are used as the values of $city and $state , respectively.
The spaceship operator (<=>) is a comparison operator introduced in PHP 7. It compares two values and returns an integer value that indicates the relationship between the values. The spaceship operator is also known as the " three-way comparison operator " because it can return one of three possible values: -1, 0, or 1.
The spaceship operator has the following syntax:
The operator returns one of three possible values:
(i) -1: if $value1 is less than $value2
(ii) 0: if $value1 is equal to $value2
(iii) 1: if $value1 is greater than $value2
The spaceship operator can be used to compare values of different types, including integers, floats, strings, and arrays. When comparing values of different types, the operator uses the same rules as the comparison operators (<, <=, >, >=), but returns the integer value instead of a boolean value.
In this example, $a is assigned a value of 10 and $b is assigned a value of 20. The spaceship operator is used to compare these two values.
The ternary operator is a shorthand way of writing an if-else statement. The ternary operator is also known as the conditional operator or the shorthand if statement. The ternary operator is denoted by ?:
Syntax: The syntax of the ternary operator in PHP is as follows
The ternary operator consists of three parts:
PHP if shorthand refers to using a shortened syntax for the if statement in PHP code. The shorthand syntax for if statements in PHP is called the ternary operator. It allows you to write a conditional statement in a single line of code.
In this version of the code, we use a traditional if statement to check if the $score variable is greater than or equal to 60. If it is, we set the $result variable to "Pass"; otherwise, we set it to "Fail". The value of the $result variable is then shown on the screen.
Here is the same code as in the previous one, but using the ternary operator. The ternary operator uses the following syntax.
Let us try writing the code with the ternary operator using the above syntax in PHP
In this example, we use the ternary operator to check if the $score variable is greater than or equal to 60. If it is, the result variable is set to "Pass"; otherwise, it is set to "Fail".
Using the ternary operator can make your code more concise and easier to read, especially if you have a simple if statement with only one action to perform. However, it's important to use it appropriately and not to overuse it, as it can make your code harder to understand if it becomes too complex.
Shorthand PHP, on one hand, can make code shorter and easier to read, but on the other hand, it can make code harder to understand and maintain. One of the benefits of shorthand PHP is that it can help reduce the amount of code needed to accomplish a task. This can be particularly useful in cases where code readability is not a top priority.
However, it can also make code harder to understand, particularly for beginners or developers who are not familiar with the shorthand notation. This can lead to bugs, errors, and other issues, which can be difficult to troubleshoot and fix.
Using shorthand PHP depends on a number of factors, including the specific use case, the developer's skill level, and the project's overall goals and constraints. Although shorthand PHP can offer significant benefits when used correctly, it is crucial to remain aware of its limitations and use it prudently to prevent potential problems in the future.
Atatus is an Application Performance Management (APM) solution that collects all requests to your PHP applications without requiring you to change your source code. However, the tool does more than just keep track of your application's performance.
Monitor logs from all of your PHP applications and systems into a centralized and easy-to-navigate user interface, allowing you to troubleshoot faster using PHP monitoring .
We give a cost-effective, scalable method to centralized PHP logging, so you can obtain total insight across your complex architecture. To cut through the noise and focus on the key events that matter, you can search the logs by hostname, service, source, messages, and more. When you can correlate log events with APM slow traces and errors, troubleshooting becomes easy.
Try your 14-day free trial of Atatus.
#1 Solution for Logs, Traces & Metrics
Monitor your entire software stack.
The PHP Ternary Operator is a shorthand syntax for an if-else statement. It provides a concise way to write conditional expressions in a single line of code.
The usage of the ternary operator is frequent when assigning values to variables based on specific conditions.
Let’s take a look at its syntax in PHP.
The basic syntax of the PHP Ternary Operator is:
Here, the condition is the expression that is evaluated. If it is true, the variable is assigned the true_value; otherwise, it is assigned the false_value.
Anyway, the ternary operator is useful for writing compact and readable code when dealing with simple conditional assignments. However, it’s important to use it judiciously and consider readability, as complex ternary expressions can become difficult to understand.
Let’s take an example of how to write shorthand using the ternary operator within PHP.
The ternary operator itself is often informally called the shorthand or conditional operator because it provides a compact syntax for expressing conditional statements in a single line. It is commonly used for quick, one-line assignments based on a condition. Here’s a brief example:
In this example, the ternary operator serves as a shorthand way to assign the boolean value true to the variable $isAdult if the condition $age >= 18 is true, and false otherwise. The term “shorthand” reflects the brevity and simplicity that the ternary operator introduces compared to the more verbose if-else statements.
In this way, we just need to understand the difference between the traditional if statement and the ternary operator. Let’s move on to the following section to delve into more details.
The Ternary Operator provides a concise way to express the conditional assignment in a single line. However, for more complex conditions or multiple actions, the traditional If-Else Statements may be preferred for better readability and maintainability.
Consequently, the Ternary Operator and traditional If-Else Statements in PHP serve distinct purposes, and their differences can be illustrated through a simple example. Consider checking whether a given number is even or odd.
PHP Ternary Operator:
The condition $number % 2 === 0 is evaluated. If true, 'even' is assigned to the $result variable; otherwise, 'odd' is assigned. The entire operation is condensed into a single line, promoting conciseness and readability for straightforward conditions.
On the other hand, with traditional If-Else Statements :
The condition is checked using the if statement. If true, 'even' is assigned to $result ; otherwise, the else block assigns 'odd' . This approach is more suitable for scenarios with complex conditions or multiple actions, as it allows for a clearer and more structured representation of the logic.
Let’s take a look at another pattern for the PHP ternary operator, specifically the nested ternary operator.
Nested ternary operators refer to the use of multiple ternary operators within a single expression. This can lead to concise yet complex conditional logic, but it requires careful consideration of readability. Here’s an example to illustrate nested ternary operators:
In this example:
Additionally, you can utilize the ternary operator with short echo tags. Let’s explore how it works through an example.
In PHP, the ternary operator can be utilized within short echo tags ( <?= ... ?> ) to conditionally output values. Short echo tags are a shorthand way of writing an echo statement.
Here’s an example demonstrating the use of the ternary operator within short echo tags:
This results in the output message “Your result: Pass” if the score is 75 or higher, and ‘Your result: Fail’ if the score is below 70.
Let’s summarize it.
the PHP Ternary Operator offers a concise syntax for expressing conditional assignments in a single line of code, providing a quick and efficient way to handle simple conditions. While it promotes brevity and readability for straightforward assignments, it’s crucial to use it judiciously, especially for more complex scenarios.
The comparison between the Ternary Operator and traditional If-Else Statements highlights the distinct purposes each serves. The Ternary Operator is suitable for streamlined, one-line assignments, while If-Else Statements are preferable for more intricate conditions or multiple actions, enhancing code readability and maintainability.
The exploration of nested ternary operators introduces a more advanced pattern, emphasizing the importance of carefully balancing conciseness with readability in complex conditional logic.
Additionally, the ability to use the ternary operator within short echo tags provides a convenient way to conditionally output values, streamlining the process of generating dynamic content in PHP.
Thank you for reading. To access more tutorials, please visit here .
PHP — P22: Shorthand Operators
My Hands Aren’t Short!
PHP shorthand operators are amazing! There, I said it. The shorthand operator combines the expression on the right with the assignment operator. The variable that appears on the left-side of the assignment operator needs to appear on the right-hand-side as well in order for you to be able to use the shorthand notation.
Let’s take a look at the following code:
If you echo out $x, 2 will be displayed.
Since the variable $x appears on both sides of the assignment operator, we can use the shorthand operator to shorten the expression $x = $x + 1. You just remove the $x from the right hand side and move the + operator in front of the = operator: $x += 1.
Shorthand operations are not limited to integers; you can use the concatenation shorthand operator to combine strings.
We can apply the same logic to the subtraction, multiplication and even the modulus operators.
Shorthand operators are used frequently throughout programming; they’re so frequent that it’s actually rare that you’ll see the long approach in the wild. There are operations that are so frequently used that even shorter operators have been created. I’m talking about the increment and decrement operators , which we covered recently.
Continue your learning with these articles
How Many Operators do You Want Already?
PHP – P21: Array Operators
PHP Array operators are operators that are used on arrays. Who would have guessed? The first operator that we’ll look at is the + operator. You would think that this operator would be used to merge two arrays, taking elements from both arrays and merging them into a new array, but that is not the case.
PHP – P22: Shorthand Operators
PHP shorthand operators are amazing! There, I said it. The shorthand operator combines the expression on the right with the assignment operator.
WHICH OPERATORS COME FIRST?
PHP – P23: OPERATOR PRECEDENCE
PHP Operator precedence just looks at which operation will be performed first. You’ve seen operator precedence in mathematics. The multiplication and division operators are executed before the addition and subtraction operators. With all of the different operators that we have in PHP, the interpreter needs to know which operation to perform in what order.
You must be logged in to post a comment.
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
I have troubles understanding how the php shorthands for if/else described here works.
The expression I'm trying to shorten is the following :
Can somebody explain me how I can apply the shorthand if/else statement in my situation ?
Thank you !
You can use ternary operator like this:
See more about Ternary Operator
In case of PHP 7, you can do it like this:
Hope this helps!
It's simple. Think of it as:
Condition ? Executes if condition is true : otherwise
In your case:
condition: isset($result[1][0])
if true: return $result[1][0]
else: return ""
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
IMAGES
VIDEO
COMMENTS
PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world.
Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP? When do they behave differently and when in the same way (if that even happens)...
In PHP, there are several shorthand assignment operators that can help simplify your code and make it more concise. Some of the common shorthand assignment operators in PHP include:
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
The PHP Conditional Assignment Operator is a shorthand method for assigning values based on ternary, Elvis, and Null Coalescing Operators.
PHP - Assignment Operators Examples - You can use assignment operators in PHP to assign values to variables. Assignment operators are shorthand notations to perform arithmetic or other operations while assigning a value to a variable.
This tutorial will teach you how to use the PHP Ternary Operator to make the code shorter and more readable.
What's the Difference Between ?? and ?: in PHP? Daniyal Hamid 3 years ago 1 min read
In looking at my Google Analytics statistics, I see a lot of visitors searching for PHP shorthand if/else (ternary) information. I've gone through my code library and picked out some examples of ternary operator usage.
Shorthand comparisons in PHP You probably already know some comparison operators in PHP. Things like the ternary ?:, the null coalescing ?? and the spaceship <=> operators. But do you really know how they work? Understanding these operators makes you use them more, resulting in a cleaner codebase.
Explore the PHP ternary shorthand, a concise way to handle conditional statements. Learn its syntax and see examples for efficient decision-making in your code.
PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world.
Use PHP assignment operator (=) to assign a value to a variable. The assignment expression returns the value assigned. Use arithmetic assignment operators to carry arithmetic operations and assign at the same time. Use concatenation assignment operator (.=)to concatenate strings and assign the result to a variable in a single statement.
PHP supports various forms of ternary and coalescing operators. This is a quick post to catch-up to all ternary and coalescing operators supports in PHP.
I preach a lot about using shorthand CSS and using MooTools to make javascript relatively shorthand, so I look towards PHP to do the same. If/Else statements aren't optimal (or necessary) in all situations. Enter ternary operators.
Shorthand Comparison in PHP Shorthand comparison, also known as the ternary operator, is a shorthand way of writing an if-else statement in PHP. It is used to assign a value to a variable based on a condition.
Ternary Operator The PHP Ternary Operator is a shorthand syntax for an if-else statement. It provides a concise way to write conditional expressions in a single line of code.
Destructuring assignment in php for objects / associative arrays Asked 9 years, 7 months ago Modified 6 months ago Viewed 77k times Part of PHP Collective
PHP shorthand operators are amazing! There, I said it. The shorthand operator combines the expression on the right with the assignment operator.
Fair. Even though PHP is a weakly typed, dynamic language, I support writing such explicit code. My answer is based on that fact that for boolean values (and most other simple types) bitwise operators are equivalent to boolean operators. But if you want to use such a shorthand, you have to give up strict equality checks (or compare to 0/1). In the end, I don't really see the point. Nonetheless ...
if/else shorthand to define a variable Asked 7 years, 8 months ago Modified 7 years, 8 months ago Viewed 5k times Part of PHP Collective