1

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");
}
1
  • explode your grab parameter and use in_array or use strpos and check for !== false (meaning it's in there) Commented Sep 7, 2016 at 2:12

2 Answers 2

2

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.