Compare variables PHP

44,828

Solution 1

$myVar = "hello";
if ($myVar == "hello") {
    //do code
}

$myVar = $_GET['param'];
if (isset($myVar)) {
    //IF THE VARIABLE IS SET do code
}


if (!isset($myVar)) {
    //IF THE VARIABLE IS NOT SET do code
}

For your reference, something that stomped me for days when first starting PHP:

$_GET["var1"] // these are set from the header location so www.site.com/?var1=something
$_POST["var1"] //these are sent by forms from other pages to the php page

Solution 2

For comparing strings I'd recommend using the triple equals operator over double equals.

// This evaluates to true (this can be a surprise if you really want 0)
if ("0" == false) {
    // do stuff
}

// While this evaluates to false
if ("0" === false) {
    // do stuff
}

For checking the $_GET variable I rather use array_key_exists, isset can return false if the key exists but the content is null

something like:

$_GET['param'] = null;

// This evaluates to false
if (isset($_GET['param'])) {
    // do stuff
}

// While this evaluates to true
if (array_key_exits('param', $_GET)) {
    // do stuff
}

When possible avoid doing assignments such as:

$myVar = $_GET['param'];

$_GET, is user dependant. So the expected key could be available or not. If the key is not available when you access it, a run-time notice will be triggered. This could fill your error log if notices are enabled, or spam your users in the worst case. Just do a simple array_key_exists to check $_GET before referencing the key on it.

if (array_key_exists('subject', $_GET) === true) {
    $subject = $_GET['subject'];
} else {
    // now you can report that the variable was not found
    echo 'Please select a subject!';
    // or simply set a default for it
    $subject = 'unknown';
}

Sources:

http://ca.php.net/isset

http://ca.php.net/array_key_exists

http://php.net/manual/en/language.types.array.php

Solution 3

If you wanna check if a variable is set, use isset()

if (isset($_GET['param'])){
// your code
}
Share:
44,828
Harigntka
Author by

Harigntka

Updated on July 09, 2022

Comments

  • Harigntka
    Harigntka almost 2 years

    How can I compare two variable strings, would it be like so:

    $myVar = "hello";
    if ($myVar == "hello") {
    //do code
    }
    

    And to check to see if a $_GET[] variable is present in the url would it be like this"

    $myVars = $_GET['param'];
    if ($myVars == NULL) {
    //do code
    }
    
    • cem
      cem almost 13 years
      Whats your question? Anyway: The first snippet does a assignment, I think you want to use "==" instead of "=". The second snippet will give you a warning (undefined index) if there is no "param" in your query string.
  • John
    John almost 13 years
    yes you can indeed, if $_get has no value, it will not be transferred to the myVar, thus it will be seen as NULL and not set by the preprocessor.