Reputation: 1762
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.
Upvotes: 86
Views: 232830
Reputation: 11984
Use isset().
if (isset($_GET["id"])) {
// do something when a parameter exists
}
You can check the existence and equality in a single condition too
if (isset($_GET["id"]) && $_GET["id"] === 'link1') {
// exists and equal to link1
}
However, it would be more convenient to define a variable first, using ??
shorthand, and then use it in a condition
$slide = $_GET["id"] ?? '';
...
if($slide === 'link1') {
// equal to link1
}
Here, an empty string is used as a default value in case parameter is not defined. You can change it to any other value.
Upvotes: 138
Reputation: 106
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') ...
Upvotes: 4
Reputation: 109
Why not just simplify it to if($_GET['id']). It will return true or false depending on status of the parameter's existence.
Upvotes: 0
Reputation: 792
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.
Upvotes: 10
Reputation: 1226
if(isset($_GET['id']))
{
// Do something
}
You want something like that
Upvotes: 71
Reputation: 157828
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"];
}
Upvotes: 4