bob jomes bob jomes - 7 months ago 12
PHP Question

Using || in if statements

If a user visits test.php?number=1 or test.php?letter=1, I want them to stay on the page. If they visit test.php, I want them to be re-directed.

I have tried to accomplish the above using the script below, however the following happens:


  • if the user visits test.php?number=1, they stay on the page.

  • If the user visits test.php?letter=1, they are re-directed.

    if(!isset($_GET['number']) === false || $_GET['letter'] === false) {
    echo '<h1>Hello</h1>';
    }else{
    header('Location: redirect.php');
    exit();
    }



Note: the value of number and letter can change! It won't always be 1!

Answer

Instead of isset() use empty() in this case as an non-existent value does not do you any good, ie. test.php?number= with no value entered for number. Ditto for letter.

The following will check if either number or letter contain a value, to which the condition will satisfy and <h1>Hello</h1> will print. Otherwise, if neither contain a value, you will be redirected.

if ( ! empty($_GET['number']) || ! empty($_GET['letter']) ) {
    echo '<h1>Hello</h1>';
}
else {
    header('Location: redirect.php');
    exit;
}