比较变量PHP

Har*_*tka 2 php string variables compare

如何比较两个变量字符串,它是这样的:

$myVar = "hello";
if ($myVar == "hello") {
//do code
}
Run Code Online (Sandbox Code Playgroud)

并检查url中是否存在$ _GET []变量,它是否会像这样"

$myVars = $_GET['param'];
if ($myVars == NULL) {
//do code
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ohn 7

    $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
 }
Run Code Online (Sandbox Code Playgroud)

作为你的参考,在第一次启动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
Run Code Online (Sandbox Code Playgroud)


Kat*_*uke 5

为了比较字符串,我建议使用三等于运算符超过双等于.

// 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
}
Run Code Online (Sandbox Code Playgroud)

为了检查$ _GET变量,我宁愿使用array_key_exists,如果密钥存在但是内容为null,则isset可以返回false

就像是:

$_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
}
Run Code Online (Sandbox Code Playgroud)

尽可能避免执行如下任务:

$myVar = $_GET['param'];
Run Code Online (Sandbox Code Playgroud)

$ _GET,取决于用户.因此,预期的密钥可用或不可用.如果在访问密钥时该密钥不可用,则会触发运行时通知.如果启用了通知,这可能会填满您的错误日志,或者在最坏的情况下,您的用户会收到垃 只需执行一个简单的array_key_exists来检查$ _GET,然后再引用它上面的键.

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';
}
Run Code Online (Sandbox Code Playgroud)

资料来源:

http://ca.php.net/isset

http://ca.php.net/array_key_exists

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