Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify if $_GET exists?

So, I have some PHP code that looks a bit like this:

<body>     The ID is       <?php     echo $_GET["id"] . "!";     ?>  </body> 

Now, when I pass an ID like http://localhost/myphp.php?id=26 it works alright, but if there is no ID like just http://localhost/myphp.php then it outputs:

The ID is Notice: Undefined index: id in C:\xampp\htdocs\myphp.php on line 9 ! 

I have searched for a way to fix this but I cannot find any way to check if a URL variable exists. I know there must be a way though.

like image 433
tckmn Avatar asked Aug 18 '12 15:08

tckmn


People also ask

How do you check if $_ GET is not empty?

<? php //Method 1 if(! empty($_GET)) echo "exist"; else echo "do not exist"; //Method 2 echo "<br>"; if($_GET) echo "exist"; else echo "do not exist"; //Method 3 if(count($_GET)) echo "exist"; else echo "do not exist"; ?>

What is if isset ($_ GET?

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.


2 Answers

You can use isset function:

if(isset($_GET['id'])) {     // id index exists } 

You can create a handy function to return default value if index doesn't 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 to validate 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); 
like image 200
Zbigniew Avatar answered Sep 26 '22 04:09

Zbigniew


   if (isset($_GET["id"])){         //do stuff     } 
like image 35
Makita Avatar answered Sep 22 '22 04:09

Makita