user6791369 user6791369 - 2 months ago 12
PHP Question

How to translate multiple parameters to a PHP conditional if statement

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");
}

Answer

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
    }
}
Comments