Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple PHP isset test

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;

?>
like image 438
JasonDavis Avatar asked Aug 08 '09 13:08

JasonDavis


People also ask

What is $_ Isset in PHP?

PHP isset() Function The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

What is if isset ($_ POST submit )) in PHP?

isset( $_POST['submit'] ) : This line checks if the form is submitted using the isset() function, but works only if the form input type submit has a name attribute (name=”submit”).

Does Isset check for NULL PHP?

The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.


2 Answers

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";
like image 182
Greg Avatar answered Oct 19 '22 08:10

Greg


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

$friendid = isset($_GET['friendid']) ? $_GET['friendid'] : 'empty';
like image 52
Philippe Gerber Avatar answered Oct 19 '22 09:10

Philippe Gerber