This question already has answers here:
What are the PHP operators "?" and ":" called and what do they do?
(10 answers)
Closed 5 years ago.
$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.
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.
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.
It is the same as:
if (isset($_POST['items']){
$items = $_POST['items'];
} else {
$items = array();
}
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>';
}
?>
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'] : "";
Basically if $_POST['items'] exists then $items gets set to it otherwise it gets set to an empty array.
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.
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.
Related
I often encounter situations like this:
function stuff()
{
$feed_data = blablabla(...);
if ($feed_data && isset($feed_data['posts'][0]['title']))
return $feed_data['posts'][0]['title'];
return false;
}
As you can see, $feed_data['posts'][0]['title'] is returned, but it's first checked with isset() to make sure it actually exists, which is not guaranteed.
If I do not include the isset() check, it can log even uglier errors about how it doesn't exist. (When things go wrong.)
Now I'm wondering if there is some way to only have to have one instance of the reference sting $feed_data['posts'][0]['title'] in my code, yet also do the check.
This is the most obvious "solution" which I've naturally tested:
$a = $feed_data['posts'][0]['title'];
if ($feed_data && isset($a))
return $a;
However, this will log the error at the first line, because you cannot assign a variable which doesn't exist!
I don't see a way around this, and it's been bothering me for a long time. I hate having duplicate code snippets like that in my code.
It seems like there ought to be a better way.
You can use a null coalescing operator:
$a = $feed_data['posts'][0]['title'] ?? false;
It checks against having a null value, if it does, return false, else return the long variable :)
Note that this was introduced with PHP 7, you can read more here
If you're specifically looking for $feed_data['posts'][0]['title'] then you don't need to check for both this value and the "parent" $feed_data array. Simply check only for this value, as one can not exist without the other.
As mentioned by treyBake you can use the ?? operator (PHP 7+) to place the value in the if statement, when the checks the value as to if the if is executed.
Combining these two points gives:
if($a = $feed_data['posts'][0]['title'] ?? false){
// Do stuff wth $a
return $a;
}
Pre PHP 7:
c'mon, update your system ;-)
NOTE: The result $a needs to be hard checked against false so that falsey values such as 0 or empty strings are not erroneously skipped (If you DO want to skip these falsey things; use empty instead of isset).
if(
($a = isset($feed_data['posts'][0]['title']) ?
$feed_data['posts'][0]['title'] : false) !== false) {
//do stuff with $a
return $a;
}
The code below works I am able to get the color of the car. Now, when the site was made professionally, some of the fields didn't get filled out. So, some of the fields either have a 0, have the word null, empty, or are empty. The one I am interested in is the color column. Some of the fields are empty.
Function getCarColor($cariD){
the rest of my sql code
$carColor = $ref['color'];
return $carColor;
}
What I am stuck in is on how to check if they are empty and add a random text inside, just so that everything looks uniform.
This is my code
Function getCarColor($cariD){
the rest of my sql code
$carColorchk = $ref['color'];
$carColor == is_null (('unspecified') ?: $carColorchk);
return $carColor;
}
Please help. I will eat some extra tamales in your name on christmas dinner.
Try:
you can use null coalesce operator if you are using php 7:
$carColor = $ref['color'] ?? 'nocolor';
or user below if php >=5.3 only
$carColor = $ref['color'] ?: 'nocolor';
There are many ways to do that. You can try the below one:
<?php
if((!empty($your_value)) && ($your_value ! =0) && ($your_value !='')){
//your Code
}
?>
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?
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.
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().
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
You can also do this (short form):
isset($testing) ? $new_variable = $testing : NULL;
JUST USE NULL TO SKIP STATEMENTS WHEN IT WRITTEN IN SHORTHAND
$a == $b? $a = 20 : NULL;
This question already has answers here:
What is ?: in PHP 5.3? [duplicate]
(3 answers)
Closed 8 years ago.
So I'm using the following php code to set variables that are received from a POST method, but I'm interested in how it works.
$var1 = isset($_REQUEST['var1']) ? $_REQUEST['var1'] : 'default';
I understand what it does, but I don't understand the syntax.
Thanks for the help :)
? is just a short and optimised notation of doing this:
if (isset($_REQUEST["var1"])) // If the element "var1" exists in the $_REQUEST array
$var1 = $_REQUEST["var1"]; // take the value of it
else
$var1 = "default"; // if it doesn't exist, use a default value
Note that you might want to use the $_POST array instead of the $_REQUEST array.
This is a short hand IF statement and from that you are assigning a value to $var1
The syntax is :
$var = (CONDITION) ? (VALUE IF TRUE) : (VALUE IF FALSE);
You probably mean ternary operator
Syntax it's same like
if(isset($_REQUEST('var1') ) {
$var1 = ? $_REQUEST('var1')
}else {
$var1 =: 'default';
}
It's the synatx of the ternary operator. It's shorthand for if/else. Please read PHP Manaul
This is a 'ternary operator', what it says is:-
If var1 is set as a post variable then set var1 to that value, otherwise setvar1 to be the string 'default'. Using traditional syntax it would be:-
if (isset($_REQUEST('var1')) { $var1 = $_REQUEST('var1'); } else { $var1 = 'default'; }
its a short way of doing an if. if you are expecting a post variable its must better to use _POST rather than request.
the "?" says if the isset($_REQUEST) is true, then do the everything between the ? and : otherwise do everything between the : and the ;
Does anybody know if there is a shortcut for the following statement in PHP?
$output = isset($some_value) ? $some_value : "Some Value Not Set";
echo $output;
This something that I often run into, where $some_value is actually very long and possibly involves a function, such as:
$output = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value) ? $this->db->get_where('my_db',array('id'=>$id))->row()->some_value) : "Some Value Not Set";
echo $output;
It seems that there should be an operator or function that does this. I could easily write one, and I am not looking for that answer, but rather if anybody knows of a built-in shortcut.
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.
http://php.net/manual/en/language.operators.comparison.php
if you need to reuse the long expression from the test after the ?, you can assign it to a variable inside the test (because assignments are expressions returning the assigned value) and use this variable after the ?:
$output = ($some_value = $this->db->get_where('my_db', array('id' => $id))->row()->some_value))
? $some_value
: "Some Value Not Set";
echo $output;
You should be setting a variable with the results of your database call before using the conditional operator for this purpose. Your example makes the database call twice.
For example:
$output = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value);
$output = $output ? $output : "Some Value Not Set";
echo $output;
And with that established, this is a good case where it's really wiser to not use the conditional operator, which really isn't meant to be used as a general purpose if-then shortcut.
You seem to be afraid of whitespace. Use it! Liberally! Your code is much eaiser to read if you add a space before and after the question mark and the colon, respectively. If your statements get too long, add a newline. Try it, it won't hurt you.
I do believe that the conditional operator is the shortcut :) For the sake of saving function calls and readability, I suggest saving the value to a variable first.
$some_value = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value);
$output = $some_value ? $some_value : "Some Value Not Set";
echo $output;
Best way is to:
$output = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value)
echo $output =($output)?$output:"Some Value Not Set";
Only executes once then!