How to check if $ _GET exists?
So, I have some PHP code that looks something like this:
<body> The ID is <?php echo $_GET["id"] . "!"; ?> </body> Now, when I pass an identifier like http://localhost/myphp.php?id=26 , it works fine, but if the identifier is missing, as soon as http://localhost/myphp.php , it outputs:
The ID is Notice: Undefined index: id in C:\xampp\htdocs\myphp.php on line 9 ! I was looking for a way to fix this, but I cannot find a way to check if the URL variable exists. I know there must be a way.
You can use the isset function:
if(isset($_GET['id'])) { // id index exists } You can create a convenient function to return the default value if the index does not exist:
function Get($index, $defaultValue) { return isset($_GET[$index]) ? $_GET[$index] : $defaultValue); } // prints "invalid id" if $_GET['id'] is not set echo Get('id', 'invalid id'); You can also try checking it at the same time:
function GetInt($index, $defaultValue) { return isset($_GET[$index]) && ctype_digit($_GET[$index]) ? (int)$_GET[$index] : $defaultValue); } // prints 0 if $_GET['id'] is not set or is not numeric echo GetInt('id', 0); if (isset($_GET["id"])){ //do stuff } This is usually a good idea:
echo isset($_GET['id']) ? $_GET['id'] : 'wtf'; This is so when you assign var to other variables, you can do everything by default in one go, rather than constantly using if to just give them a default value if they are not set.
Use empty() with negation (for test, if not empty)
if(!empty($_GET['id'])) { // if get id is not empty } You can use array_key_exists() built-in function:
if (array_key_exists('id', $_GET)) { echo $_GET['id']; } or isset() built-in function:
if (isset($_GET['id'])) { echo $_GET['id']; } Try:
if(isset($_GET['id']) && !empty($_GET['id'])){ echo $_GET["id"]; }