Using Ternary Operator without the Else statement PHP

26,747

Solution 1

Since PHP 5.3 you can do this:

!isset($testing) ?: $new_variable = $testing;

As you can see, it only uses the part if the condition is false, so you have to negate the isset expression.

UPDATE

Since PHP 7.0 you can do this:

$new_variable = $testing ?? null;

As you can see, it returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

UPDATE

Since PHP 7.4 you can do this:

$new_variable ??= $testing;

It leaves $new_variable alone if it isset and assigns $testing to it otherwise.

Solution 2

Just set it to NULL like this:

$new_variable = (isset($testing) ? $testing : NULL);

The you variable would return false with a isset() check.

You can read more about NULL in the manual.

And a quote from there:

The special NULL value represents a variable with no value. NULL is the only possible value of type null.

A variable is considered to be null if:

  • it has been assigned the constant NULL.
  • it has not been set to any value yet.
  • it has been unset().

Solution 3

Since PHP 7.0 you can do the following, without getting an ErrorException "Trying to get property 'roomNumber' of non-object":

$house = new House();
$nr = $house->tenthFloor->roomNumbers ?? 0

Assuming the property "tenthFloor" does not exist in the Class "House", the code above will not throw an Error. Whereas the code below will throw an ErrorException:

$nr = $house->tenthFloor->roomNumbers ? $house->tenthFloor->roomNumbers : 0

Solution 4

You can also do this (short form):

isset($testing) ? $new_variable = $testing : NULL;
Share:
26,747
Longblog
Author by

Longblog

Updated on October 22, 2020

Comments

  • Longblog
    Longblog over 3 years

    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:

    if ( isset($testing) {
      $new_variable = $testing;
    }
    

    Will only set $new_variable if $testing exists. Now I can do

    $new_variable = (isset($testing) ? $testing : "");
    

    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

    $new_variable = (isset($testing) ? $testing);
    

    and it returned errors. I also tried

    $new_variable = (isset($testing) ? $testing : );
    

    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:

    $yes_this_test = "IDK";
    $setforsure = "for sure";
    $list = new stdClass;
    $list->DefinitelySet = $setforsure;
    $list->MaybeSet = (isset($yes_this_test) ? $yes_this_test : NULL);
    $list->MaybeSet = (isset($testing) ? $testing : NULL);
    print_r($list);
    

    But obviously MaybeSet gets set to NULL because (isset($testing) comes after (isset($yes_this_test) and it returns

    stdClass Object ( [DefinitelySet] => for sure [MaybeSet] => )
    

    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

    if ( isset($yes_this_test ) {
      $list->MaybeSet = $yes_this_test;
    }
    elseif ( isset($testing) ) {
      $list->MaybeSet = $testing;
    }
    

    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?

  • Longblog
    Longblog about 9 years
    Perfect! Thank you. I always assumed NULL was pretty much the same as empty. I guess I should assume less and read more. ;)
  • Longblog
    Longblog about 9 years
    Bah, actually after testing it just now, it still appends the variable to a list, just as an empty variable. I don't know if this will work because I'm going to have to use it for an array of parameters using $_POST variables as parameters. I don't know in what order the $_POST variables will come through, so I might end up with a NULL parameter, even though one of the $_POST variables is set. I'll explain further above.
  • Rizier123
    Rizier123 about 9 years
    @Longblog yeah just edit your question and put it in there, so that I see what you mean
  • Longblog
    Longblog about 9 years
    OK I have added additional details as well as an example. Thanks for your help.
  • Rizier123
    Rizier123 about 9 years
    @Longblog Just add this at the end: $list = (object) array_filter((array)$list, function ($v){ return !is_null($v); }); And this will remove all values which have the value NULL. The problem is that this is in a class, so it's just like a defined property with no value
  • Longblog
    Longblog about 9 years
    Thanks for the response Rizier123. I don't think that will solve the problem of the variable value being overwritten by a NULL value though. Lets say $_POST["option1"] is set, but $_POST["option2"] isn't. As my code above runs, $_POST["option2"] will overwrite the value of option 1, changing it to a null value. Then the function you posted above will remove it completely from $list and the code won't have the proper variable required for the API. I think I'm going to have to use normal if/else statements in this case. I can't see a way around it unless something exists that I'm unaware of.
  • Longblog
    Longblog about 9 years
    What I really need is shorthand for a statement that says, if x is set, y = x, else do nothing. Does this exist?
  • Rizier123
    Rizier123 about 9 years
    @Longblog So if I understand the problem correctly you have X amount of POST variables. You go through the first and if it is set then result = POST1 and so on and if one post isn't set it shouldn't overwrite anything, right?
  • Longblog
    Longblog about 9 years
    Correct. To clarify, if there's 3 possible POST variables for this category, only 1 will be set. So I have to assign the one that is set to a predetermined parameter name. I can't have the two that aren't set overwrite the one that is set with NULL or empty. I can't just name all the possible form input's for the category the same(even though this seems like the best idea), because of reasons more complex than I have space to explain here. I know I can do it with normal if/elseif statements, I'd just like to know if there's shorthand for it.
  • Longblog
    Longblog about 9 years
    I thought I figured it out just now and tried !$list->MaybeSet as the else portion of the ternary, but it still returns MaybeSet as a key with an empty value. Doh!
  • Rizier123
    Rizier123 about 9 years
    I'm not quite sure if this is what you need and otherwise I think you need to use if/else, but try this: $postKeys = ["a", "b", "c"]; $result = array_reduce($postKeys, function($result, $v){ return (isset($_POST[$v])?$_POST[$v]:$result); }, "defaultValue"); Just fill the $postKeys array with the POST variable keys and $result will hold the final value (You can also set a default value if all variables doesn't exists)
  • Daan
    Daan about 8 years
    null is just a valid value in PHP, so this does not returning "nothing".
  • ahnbizcad
    ahnbizcad over 3 years
    The fact that PHP allows empty value in the "truthy" slot but not the "falsey" slot is ridiculous. What goes on in the PHP language maintainers' minds? !isset($testing) ? : $new_variable = $testing; but not !isset($testing) ? $new_variable = $testing;
  • patrickj
    patrickj about 3 years
    @ahnbizcad It's not an actual empty value, just syntactic sugar to use the first operand. I agree it would be nice to have an equivalent that uses null if the third operand is omitted, but that would probably require a new operator.
  • ahnbizcad
    ahnbizcad about 3 years
    Maybe the syntactic sugar sucks and is actually syntactic aspartame.
  • achasinh
    achasinh over 2 years
    Love the "null coalescing assignment operator" (??=) addition in PHP 7.4