开发者

Compare variables PHP

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

$myVar = "hello";
if ($myVar == "hello") {
//do code
}
开发者_如何学JAVA

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
}


$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


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


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

if (isset($_GET['param'])){
// your code
}


To compare a variable to a string, use this:

if ($myVar == 'hello') {
    // do stuff
}

To see if a variable is set, use isset(), like this:

if (isset($_GET['param'])) {
    // do stuff
}


All this information is listed on PHP's website under Operators

http://php.net/manual/en/language.operators.comparison.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜