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;
?>
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:
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).
Currently you're working with the ternary operator:
Break it down to an
if-else
statement and it looks like this:Look at what's really happening in the
if
statement: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 firstif
condition is now false and passes it on to theelse
option.In this case, set the value of the
$friendid
variable toempty
.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.if friendid is NOT set, friendid = friendid otherwise friendid = empty
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$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.Remove the
!
. You don't want to negate the expression.The best solution for this question, i.e. if you also need to 'check for the empty string', is empty().
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, ...