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;
Related
I'm used to JavaScript where I often write things like this: const ref = obj.arr || (obj.arr = []);.
With one line of code, this gives me a reference on obj.arr after having initialized it to empty array if it didn't exist.
I'm trying to do the same in PHP but I'm struggling with ampersands, since the assignation is done by copy of value by default. Here is my failing attempt which I thought it would work:
$ref= &$obj['arr'] ?? &($obj['arr'] = []);
If I understand your question correctly, a ternary operator should suffice:
$obj['arr'] = isset($obj['arr']) ? $obj['arr'] : [];
$ref = &$obj['arr']);
Dudes,
is there a more concise way to write the statement below? If I don't check if an array key exists I get a PHP warning. However, the below is a bit too, ehm, wordy.
Thanks!
$display_flag = false;
if (array_key_exists('display_flag',$pref_array) {
$display_flag = $pref_array['display_flag'];
}
Since PHP 7 you can use the new null coalescing operator.
$display_flag = $pref_array['display_flag'] ?? false;
If $display_flag is a boolean:
$display_flag = isset($pref_array['display_flag']) && $pref_array['display_flag'];
If it's a string:
$display_flag = isset($pref_array['display_flag']) ? $pref_array['display_flag'] : false;
// Get the $pref_array from wherever
$default_prefs = array(
"display_flag" => false,
);
$pref_array = array_merge($default_prefs, $pref_array);
// Now you know it's always defined with default values
The way you have it is fine, as you should validate if the value actually exists, but you could also do a ternary op:
$display_flag = (isset($pref_array['display_flag'])) ? (bool) $pref_array['display_flag'] : false;
I typecast the contents of display_flag to bool if it is set, so you are ensured a boolean value in either case.
Also you could (but I don't recommend it), squelch the warning with the #:
$display_flag = #$pref_array['display_flag'];
Another simpler option is:
array_get($variable, 'keyName', null)
The third argument is the default value.
I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it. I am looking at php.net isset code, and I see isset($_GET['something']) ? $_GET['something'] : ''
I understand normal isset operations, such as if(isset($_GET['something']){ If something is exists, then it is set and we will do something } but I don't understand the ?, repeating the get again, the : or the ''. Can someone help break this down for me or at least point me in the right direction?
It's commonly referred to as 'shorthand' or the Ternary Operator.
$test = isset($_GET['something']) ? $_GET['something'] : '';
means
if(isset($_GET['something'])) {
$test = $_GET['something'];
} else {
$test = '';
}
To break it down:
$test = ... // assign variable
isset(...) // test
? ... // if test is true, do ... (equivalent to if)
: ... // otherwise... (equivalent to else)
Or...
// test --v
if(isset(...)) { // if test is true, do ... (equivalent to ?)
$test = // assign variable
} else { // otherwise... (equivalent to :)
In PHP 7 you can write it even shorter:
$age = $_GET['age'] ?? 27;
This means that the $age variable will be set to the age parameter if it is provided in the URL, or it will default to 27.
See all new features of PHP 7.
That's called a ternary operator and it's mainly used in place of an if-else statement.
In the example you gave it can be used to retrieve a value from an array given isset returns true
isset($_GET['something']) ? $_GET['something'] : ''
is equivalent to
if (isset($_GET['something'])) {
echo "Your error message!";
} else {
$test = $_GET['something'];
}
echo $test;
Of course it's not much use unless you assign it to something, and possibly even assign a default value for a user submitted value.
$username = isset($_GET['username']) ? $_GET['username'] : 'anonymous'
You have encountered the ternary operator. It's purpose is that of a basic if-else statement. The following pieces of code do the same thing.
Ternary:
$something = isset($_GET['something']) ? $_GET['something'] : "failed";
If-else:
if (isset($_GET['something'])) {
$something = $_GET['something'];
} else {
$something = "failed";
}
It is called the ternary operator. It is shorthand for an if-else block. See here for an example http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
? is called Ternary (conditional) operator : example
What you're looking at is called a Ternary Operator, and you can find the PHP implementation here. It's an if else statement.
if (isset($_GET['something']) == true) {
thing = isset($_GET['something']);
} else {
thing = "";
}
If you want an empty string default then a preferred way is one of these (depending on your need):
$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);
If the url parameter something doesn't exist in the url then $_GET['something'] will return null
strval($_GET['something']) -> strval(null) -> ""
and your variable $value is set to an empty string.
trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)
intval() if only numeric values are expected and the default is zero. intval(null) -> 0
Cases to consider:
...&something=value1&key2=value2 (typical)
...&key2=value2 (parameter missing from url $_GET will return null for it)
...&something=+++&key2=value (parameter is " ")
Why this is a preferred approach:
It fits neatly on one line and is clear what's going on.
It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';
Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';
It's compatible with older and newer php.
Update
Strict mode may require something like this:
$str_value = strval(#$_GET['something']);
$trimmed_value = trim(#$_GET['something']);
$int_value = intval(#$_GET['somenumber']);
Considering that:
The isset() construct returns TRUE if a variable is set and not NULL
The is_null() function throws a warning if the variable is not set
Is there a way to test whether a variable exists, no matter it's NULL or not, without using the # operator to suppress the notice?
EDIT
Together with your first replies, I've been thinking about this and I'm getting the conclusion that inspecting get_defined_vars() is the only way to distinguish between a variable set to NULL and an unset variable. PHP seems to make little distinctions:
<?php
$exists_and_is_null = NULL;
// All these are TRUE
#var_dump(is_null($exists_and_is_null));
#var_dump(is_null($does_not_exist));
#var_dump($exists_and_is_null===NULL);
#var_dump($does_not_exist===NULL);
#var_dump(gettype($exists_and_is_null)=='NULL');
#var_dump(gettype($does_not_exist)=='NULL');
?>
$result = array_key_exists('varname', get_defined_vars());
As you already found out, you cannot :
rely on isset, as it return false for a variable that's null.
use $not_exists===null, as it'll raise a notice.
But you could be able to use a combinaison of :
get_defined_vars to get the list of existing variables, including those which are null,
and array_key_exists to find out if an entry exists in that list.
For instance :
$exists_and_null = null;
$exists_and_not_null = 10;
$defined_vars = get_defined_vars();
// true
var_dump(array_key_exists('exists_and_null', $defined_vars)
&& $defined_vars['exists_and_null']===null);
// false
var_dump(array_key_exists('exists_and_not_null', $defined_vars)
&& $defined_vars['exists_and_not_null']===null);
// false
var_dump(array_key_exists('not_exists', $defined_vars)
&& $defined_vars['not_exists']===null);
A couple of notes :
In the first case, the variable exists => there is an entry in the list returned by get_defined_vars, so the second part of the condition is evaluated
and both parts of the condition are true
In the second case, the variable exists too, but is null
which means the first part of the condition is true, but the second one is false,
so the whole expression is false.
In the third case, the variable doesn't exist,
which means the first part of the condition is false,
and the second part of the condition is not evaluated -- which means it doesn't raise a notice.
But note this is probably not that a good idea, if you care about performances : isset is a language construct, and is fast -- while calling get_defined_vars is probably much slower ^^
I would argue here that any code requiring such a comparison would have gotten its semantics wrong; NULL is an unset value in a language that has no straightforward way of distinguishing between the two.
I used a self created function to check this easily, keep in mind it will fire off a PHP warning (I only monitor E_ERROR when I develop).
function isNullOrEmpty( $arg )
{
if ( !is_array( $arg ) )
{
$arg = array( $arg );
}
foreach ( $arg as $key => $value )
{
if( $value == null || trim($value) == "" )
{
return true;
}
}
return false;
}
if (isset($var) && (is_null($var)) {
print "\$var is null";
}
This should do the trick.
This below does not seem to work how I would expect it, event though $_GET['friendid'] = 55 it is returning NULL
<?PHP
$_GET['friendid'] = 55;
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
echo $friendid;
exit;
?>
As of PHP 7's release, you can use the null-coalescing operator (double "?") for this:
$var = $array["key"] ?? "default-value";
// which is synonymous to:
$var = isset($array["key"]) ? $array["key"] : "default-value";
In PHP 5.3+, if all you are checking on is a "truthy" value, you can use the "Elvis operator" (note that this does not check isset).
$var = $value ?: "default-value";
// which is synonymous to:
$var = $value ? $value : "default-value";
Remove the !. You don't want to negate the expression.
$friendid = isset($_GET['friendid']) ? $_GET['friendid'] : 'empty';
If you're lazy and risky, you can use error control operator # and short form of ternary operator.
$friendid = #$_GET['friendid']?: 'empty';
Currently you're working with the ternary operator:
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
Break it down to an if-else statement and it looks like this:
if(!isset($_GET['friendid']))
$friendid = $_GET['friendid'];
else
$friendid = 'empty';
Look at what's really happening in the if statement:
!isset($_GET['friendid'])
Note the exclamation mark (!) in front of the isset function. It's another way to say, "the opposite of". What you're doing here is checking that there is no value already set in $_GET['friendid']. And if so, $friendid should take on that value.
But really, it would break since $_GET['friendid'] doesn't even exist. And you can't take the value of something that isn't there.
Taking it from the start, you have set a value for $_GET['friendid'], so that first if condition is now false and passes it on to the else option.
In this case, set the value of the $friendid variable to empty.
What you want is to remove the exclamation and then the value of $friendid will take on the value of $_GET['friendid'] if it has been previously set.
The best solution for this question, i.e. if you also need to 'check for the empty string', is empty().
$friendid = empty($_GET['friendid']) ? 'empty' : $_GET['friendid'];
empty() not only checks whether the variable is set, but additionally returns false if it is fed anything that could be considered 'empty', such as an empty string, empty array, the integer 0, boolean false, ...
I am using Null coalescing operator operator in if condition like this
if($myArr['user'] ?? false){
Which is equivalent to
if(isset($myArr['user']) && $myArr['user']){
From your reply to Philippe I think you need to have a look at the differences between empty and isset.
To summarise, isset() will return boolean TRUE if the variable exists. Hence, if you were to do
$fid = $_GET['friendid'] = "";
$exists = isset($fid);
$exists will be TRUE as $_GET['friendid'] exists. If this is not what you want I suggest you look into empty. Empty will return TRUE on the empty string (""), which seems to be what you are expecting. If you do use empty, please refer to the documentation I linked to, there are other cases where empty will return true where you may not expect it, these cases are explicitly documented at the above link.
if friendid is NOT set, friendid = friendid otherwise friendid = empty
Okay, I may have been having a similar issue not being familiar with the ! situation as jasondavis had.
Kind of confusing but finding out not having the ! as in... isset($avar) compared to !isset($avar) can make quite the difference.
So with the ! in place, is more stating a YES as in
since $_GET['friendid'] = 55; has been initialized...
tell me 'no' - the opposite - that it hasn't and set it to empty.
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
where not having the ! tells me yes it has something in it, leave it be.
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
Was far less confusing with if A$="" then.... work it. ( or if $A="" for those of PHP ).
I find this use of strings and variables all as strings to be very daunting at times. Even through the confusion, I can actually understand why... just makes things a tad difficult to grasp for me.
For me, if I need to know BOTH are true
key is set
value is truthy
and if not, use another result:
the shortest way is
$result = ($arr['b'] ?? 0) ?: $arr['a'];
(ie. if b is_set AND has a real value, use it. Otherwise use a)
So in this scenario:
$arr = ['a' => 'aaa', 'b' => 'bbb'];
$result = 'aaa'