18
$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.

William Perron
  • 485
  • 7
  • 16
payling
  • 2,466
  • 5
  • 33
  • 44

8 Answers8

45

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.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • It’s *A* ternary operator and not the ternary operator. Just as there are many binary opreators (+, -, *, /, &&, ||, ^, etc.). – Gumbo May 20 '09 at 18:19
  • The PHP documentation called it 'the' :X – Paolo Bergantino May 20 '09 at 18:26
  • 1
    it's usually called the "conditional operator" officially in most languages, but is often also called *the* ternary operator because in most languages, it is the only ternary operator. It may well be that when PHP was created, they chose "the ternary operator" as the official name, but I'm not sure. – rmeador May 20 '09 at 18:59
  • 14
    fixed my answer to reflect the unexpected uproar over the usage of 'the' – Paolo Bergantino May 20 '09 at 19:00
  • 1
    From the same link, "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." – gradbot May 20 '09 at 20:58
  • 2
    There's more than one ternary operator in PHP, Gumbo? – Jarret Hardie May 21 '09 at 01:01
18

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.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
2

It is the same as:

if (isset($_POST['items']){
    $items = $_POST['items'];
} else {
    $items = array();
}
Jeroen
  • 3,399
  • 1
  • 22
  • 25
2

Look at Paolo's answer to understand the ternary operator.

To do what you are looking at doing you might want to use a session variable.

At the top of your page put this (because you can't output anything to the page before you start a session. I.E. NO ECHO STATEMENTS)

session_start();

Then when a user submits your form, save the result in this server variable. If this is the first time the user submitted the form, just save it directly, otherwise cycle through and add any value that is not empty. See if this is what you are looking for:

HTML CODE (testform.html):

<html>
    <body>
    <form name="someForm" action="process.php" method="POST"> 
        <input name="items[]" type="text">
        <input name="items[]" type="text">
        <input name="items[]" type="text">
        <input type="submit">
    </form>
    </body>
</html>

Processing code (process.php):

<?php
session_start();

if(!$_SESSION['items']) {
    // If this is the first time the user submitted the form,
    // set what they put in to the master list which is $_SESSION['items'].
    $_SESSION['items'] = $_POST['items'];
}
else {
    // If the user has submitted items before...
    // Then we want to replace any fields they changed with the changed value
    // and leave the blank ones with what they previously gave us.
    foreach ($_POST['items'] as $key => $value) {
        if ($value != '') { // So long as the field is not blank
            $_SESSION['items'][$key] = $value;
        }
    }
}


// Displaying the array.
foreach ($_SESSION['items'] as $k => $v) {
    echo $v,'<br>';
}
?>
Joe Bubna
  • 296
  • 1
  • 2
  • 7
1

yup... it is ternary operator

a simple and clear explanation provided here, in which the author said it is like answering : “Well, is it true?”

the colon separates two possible values (or). the first value will be chosen if the test expression is true. the second (behind the colon) will be chosen if the first answers is false.

ternary operator very helpfull in creating variable in php 7.x, free of notice warning. For example"

$mod = isset($_REQUEST['mod']) ? $_REQUEST['mod'] : "";
kenorb
  • 155,785
  • 88
  • 678
  • 743
Cholis
  • 25
  • 5
  • Instead of linking to the site, please include a brief summary of the pages contents. If they change the pages location later, this answer won't be very helpful. – davelupt Sep 16 '17 at 06:53
  • davelupt, thanks for 'the brief summary' suggestion. i added it. – Cholis Sep 16 '17 at 07:21
0

I figured it's also worth noting that ?: is a separate operator, where:

$one = $two ?: $three;
$one = two() ?: three();

is shorthand for:

$one = $two ? $two : $three;
$one = two() ? two() : three();

Aside from typing less, the runtime advantage is that, if using a function like two(), the function would only be evaluated once using the shorthand form, but possibly twice using the long form.

Ky -
  • 30,724
  • 51
  • 192
  • 308
0

Basically if $_POST['items'] exists then $items gets set to it otherwise it gets set to an empty array.

Tom
  • 702
  • 7
  • 16
  • is it possible to store only specific items from the item array or does it have to overwrite the entire array? – payling May 20 '09 at 18:32
0

It is a ternary operator that essentially says if the items key is in the $_POST then set $items to equal the value of $_POST['items'] else set it to a null array.

xenon
  • 1,435
  • 19
  • 35