...">

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.

+49
html php
Aug 18 2018-12-18T00:
source share
7 answers

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); 
+113
Aug 18 2018-12-18T00:
source share
  if (isset($_GET["id"])){ //do stuff } 
+17
Aug 18 2018-12-18T00:
source share

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.

+9
Aug 18 2018-12-18T00:
source share

You are using php isset

Example

 if (isset($_GET["id"])) { echo $_GET["id"]; } 
+5
Aug 18 2018-12-18T00:
source share

Use empty() with negation (for test, if not empty)

 if(!empty($_GET['id'])) { // if get id is not empty } 
+4
Aug 18 2018-12-18T00:
source share

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']; } 
+4
Aug 18 2018-12-18T00:
source share

Try:

 if(isset($_GET['id']) && !empty($_GET['id'])){ echo $_GET["id"]; } 
0
May 16 '16 at 9:31
source share



All Articles