Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare variables PHP

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
}
like image 530
Harigntka Avatar asked Jun 04 '11 22:06

Harigntka


2 Answers

$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
like image 130
John Avatar answered Sep 23 '22 00:09

John


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

like image 37
Katsuke Avatar answered Sep 25 '22 00:09

Katsuke