This question already has an answer here:
$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.
That last part is known as the conditional operator. Basically it is a condensed
if/else
statement.It works like this:
Also here is some pseudo-code that may be simpler:
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.
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"
I figured it's also worth noting that
?:
is a separate operator, where:is shorthand for:
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.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)
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):
Processing code (process.php):
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.
This is a ternary operator:
The expression
(expr1) ? (expr2) : (expr3)
evaluates toexpr2
ifexpr1
evaluates toTRUE
, andexpr3
ifexpr1
evaluates toFALSE
.