Ternary operator php without else
Can you use the Ternary Operator in PHP without the closing 'else' statement? I've tried it and it's returning errors. Google search isn't yielding anything, so I think the answer is probably no. I just wanted to double check here. For instance: Show
Will only set $new_variable if $testing exists. Now I can do
but that returns an empty variable for $new_variable if $testing isn't set. I don't want an empty variable if it's not set, I want the $new_variable to not be created. I tried
and it returned errors. I also tried
and it also returned errors. Is there a way to use the Ternary Operator without the attached else statement, or am I stuck writing it out longhand? EDIT: Following Rizier123's advice, I tried setting the 'else' part of the equation to NULL, but it still ends up appending a key to an array. The value isn't there, but the key is, which messes up my plans. Please allow me to explain further. The code is going to take a bunch of $_POST variables from a form and use them for parameters in a stdClass which is then used for API method calls. Some of form variables will not exist, as they all get applied to the same variable for the API call, but the user can only select one. As an example, maybe you can select 3 items, whichever item you select gets passed to the stdClass and the other 2 don't exist. I tried this:
But obviously MaybeSet gets set to NULL because (isset($testing) comes after (isset($yes_this_test) and it returns
I won't know what order the $_POST variables are coming in, so I can't really structure it in such a way to make sure the list gets processed in the correct order. Now I know I can do something like
But I was hoping there was a shorthand for this type of logic, as I have to write dozens of these. Is there an operator similar to the Ternary Operator used for if/elseif statements? Scout APM helps PHP developers pinpoint N+1 queries, memory leaks & more so you can troubleshoot fast & get back to coding faster. Start your free 14-day trial today. You probably already know some comparison operators in PHP. Things like the ternary Before looking at each operator in depth, here's a summary of what each of them does:
# Ternary operatorThe ternary operator is a shorthand for the
You can write this:
If
this 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 Back to ternary operators: do you know which expressions evaluate to The ternary operator will use its lefthand operand when the condition evaluates to Examples would be 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 follow me on Twitter or subscribe to my newsletter: # Shorthand ternary operatorSince PHP 5.3, it's possible to leave out the lefthand operand, allowing for even shorter expressions:
In this case, the value of 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. # Chaining ternary operatorsThe 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 I believe the right thing to do is to avoid nested ternary operators alltogether. 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. # Null coalescing operatorDid 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
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. # Null coalescing on arraysThis operator is especially useful in combination with arrays, because of its acts like
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 existance of array keys. It will either trigger an error or return a boolean, instead of the real lefthand operand's value.
# Null coalesce chainingThe null coalescing operator can easily be chained:
# Nested coalescingIt's possible to use the null coalescing operator on nested object properties, even when a property in the chain is
# Null coalescing assignment operatorIn PHP 7,4, we can expect an even shorter syntax called the "null coalescing assignment operator".
In this example,
# Spaceship operatorThe 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:
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. # Comparing objectsThe 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. # Sort functionsOne 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 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! FootnotesA summary about array + array in PHP Array destructuring in PHP Attributes in PHP 8 — A close look at attributes, also known as annotations Array merge vs. + Can we use if without else in PHP?An if statement by its self is absolutely fine. If you have a series of conditions where only one will be true it's better to put the most likely first, then use else if on the subsequent ones so that PHP doesn't have to keep evaluating each condition.
Does PHP have a ternary operator?The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.
Does ternary need else?A ternary operation is called ternary because it takes 3 arguments, if it takes 2 it is a binary operation. It's an expression returning a value. If you omit the else you would have an undefined situation where the expression would not return a value. You can use an if statement.
How use ternary operator in if condition in PHP?It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2);
|