views:

414

answers:

4

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;

?>
+4  A: 

Remove the !. You don't want to negate the expression.

$friendid = isset($_GET['friendid']) ? $_GET['friendid'] : 'empty';
Philippe Gerber
Ok that works however I don't understand why this happens, $_GET['friendid'] = ''; does not show empty, shouldn't this be considered a null value?
jasondavis
'' is an empty string, but the variable is still set.
sixfoottallrabbit
That sucks so I have to check for an empty value as well I guess
jasondavis
That has nothing to do with sucking, but with the fact that a variable can be declared ($var) or initialized ($var = 'bla'). a non-declared variable and a variable declared and initialized as an empty string is not the same.
Philippe Gerber
A: 

if friendid is NOT set, friendid = friendid otherwise friendid = empty

Alix Axel
A: 

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.

HTH.

mdec
+1  A: 

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.

random