What does ? ... : ... do? [duplicate]

$items = (isset($_POST['items'])) ? $_POST['items'] : array();

I don't understand the last snippet of this code "? $_POST['items'] : array();"

What does that combination of code do exactly?

I use it to take in a bunch of values from html text boxes and store it into a session array. But the problem is, if I attempt to resubmit the data in text boxes the new array session overwrites the old session array completely blank spaces and all.

I only want to overwrite places in the array that already have values. If the user decides to fill out only a few text boxes I don't want the previous session array data to be overwritten by blank spaces (from the blank text boxes).

I'm thinking the above code is the problem, but I'm not sure how it works. Enlighten me please.


Solution 1:

This is a ternary operator:

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Solution 2:

That last part is known as the conditional operator. Basically it is a condensed if/else statement.

It works like this:

$items =
    // if this expression is true
    (isset($_POST['items'])) 
    // then "$_POST['items']" is assigned to $items
    ? $_POST['items'] 
    // else "array()" is assigned
    : array();

Also here is some pseudo-code that may be simpler:

$items = (condition) ? value_if_condition_true : value_if_condition_false;

Edit: Here is a quick, pedantic side-note: The PHP documentation calls this operator a ternary operator. While the conditional operator is technically a ternary operator (that is, an operator with 3 operands) it is a misnomer (and rather presumptive) to call it the ternary operator.

Solution 3:

It is the same as:

if (isset($_POST['items']){
    $items = $_POST['items'];
} else {
    $items = array();
}