82

I have a URL which i pass parameters into

example/success.php?id=link1

I use php to grab it

$slide = ($_GET["id"]);

then an if statement to display content based on parameter

<?php  if($slide == 'link1') { ?>
   //content
 } ?>

Just need to know in PHP how to say, if the url param exists grab it and do the if function, if it doesn't exist do nothing.

Thanks Guys

웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
user2389087
  • 1,692
  • 3
  • 17
  • 39
  • 1
    it's called isset(). `if (isset($_GET['...'])) { $slide = $_GET['...']; if ($slide == 'link1): ?> content ` – Royal Bg Aug 16 '13 at 10:29

6 Answers6

130

Use isset()

$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

EDIT: This is added for the completeness sake. $_GET in php is a reserved variable that is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.

$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
  • Older versions of PHP would let a simple `if($_GET['id']!='')` suffice. Stricter versions require this more explicit check I learned the hard way. While slightly annoying, I can appreciate that explicit and intentional coding builds great habits everywhere else and is a better practice, fundamentally. (can you tell I learned PHP on the web since the early 2000s?) – jeffkee Feb 06 '23 at 02:29
71
if(isset($_GET['id']))
{
    // Do something
}

You want something like that

rich
  • 1,224
  • 1
  • 19
  • 36
10

Here is the PHP code to check if 'id' parameter exists in the URL or not:

if(isset($_GET['id']))
{
   $slide = $_GET['id'] // Getting parameter value inside PHP variable
}

I hope it will help you.

4

It is not quite clear what function you are talking about and if you need 2 separate branches or one. Assuming one:

Change your first line to

$slide = '';
if (isset($_GET["id"]))
{
    $slide = $_GET["id"];
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
2

I know this is an old question, but since php7.0 you can use the null coalescing operator (another resource).

It similar to the ternary operator, but will behave like isset on the lefthand operand instead of just using its boolean value.

$slide = $_GET["id"] ?? 'fallback';

So if $_GET["id"] is set, it returns the value. If not, it returns the fallback. I found this very helpful for $_POST, $_GET, or any passed parameters, etc

$slide = $_GET["id"] ?? '';

if (trim($slide) == 'link1') ...
hjelmeir
  • 86
  • 1
  • 1
  • 8
0

Why not just simplify it to if($_GET['id']). It will return true or false depending on status of the parameter's existence.

jimshot
  • 109
  • 1
  • 1
  • 9