Reputation: 35
Let's say I have the following url: example.php?grab=1,3&something=...
grab
has two values, how can I translate that to a conditional if statement.
For example, if count
is a variable and you want to calculate if count
is equal to one of the grab
values.
$grab = $_GET["grab"];
$count = 4;
if($count == $grab(values)) {
alert("True");
}
Upvotes: 1
Views: 70
Reputation: 4372
Method#1: Reformat URL and Use PHP in_array()
Why not reformat your url to something like this: example.php?grab[]=1&grab[]=3&something=...
which automatically returns the grab
value as an array in PHP?
And then do something like:
if(isset($_GET['grab']) && in_array(4, $_GET['grab'])) {
// do something
}
Method#2: Split String into Array and Use PHP in_array()
If you do not wish to reformat your url, then simply split the string into an array using php's explode function and check if value exists, for example:
if(isset($_GET['grab'])) {
$grab_array = explode(",", $_GET['grab'])
if(in_array(4, $grab_array)) {
// do something
}
}
Method#3: Use Regular Expressions
You could also use regular expressions to check for a match.
Upvotes: 0
Reputation: 41893
If its always going to be ,
that glues the values, just explode
them, that turns them into an array
. Then just use your resident array functions to check. In this example, in_array
:
if(!empty($_GET['grab'])) {
$grab = $_GET["grab"];
$count = 4;
$pieces = explode(',', $grab);
if(in_array($count, $pieces)) {
// do something here if found
}
}
Sidenote: If you try to devise your url to be like this:
example.php?grab[]=1&grab[]=3&something
You wouldn't need to explode it at all. You can just get the values, and straight up use in_array
.
The example above grab
already returns it an array:
if(!empty($_GET['grab'])) {
$grab = $_GET["grab"];
$count = 4;
if(in_array($count, $grab)) {
// do something here if found
}
}
Upvotes: 2