Search code examples
phpvariableswampechoisset

Why does checking if a variable exists only return a 1 or 0 instead of the value?


I'm setting the following variables at the top of a page:

$pin = $_GET['Pin'];
$action = $_GET['action'];
$bookingref = $_GET['bookingref'];
$phone1 = $_GET['number1'];
$phone2 = $_GET['number2'];

I'm using WAMP to develop my site, and when the page loads, I get an 'Undefined Index' warning for each one.

So I thought I'll put them inside an isset, to check if they exist.

$pin = isset($_GET['Pin']);
$action = isset($_GET['action']);
$bookingref = isset($_GET['bookingref']);
$phone1 = isset($_GET['number1']);
$phone2 = isset($_GET['number2']);

But now when I try to echo the values I just get either a blank space or 1.

How can I echo the value of the variable, and keep the isset check?


Solution

  • Because you're assigning the return value of isset(), which is TRUE or FALSE.

    You need to use isset() to check if they exist, then assign the variable if it does.

    if(isset($_GET['Pin'])){
        $pin = $_GET['Pin']
    }
    

    Or a shorthand ternary alternative

    $pin = (!isset($_GET['Pin'])) ?: $_GET['Pin'];