比较变量PHP

时间:2011-06-04 22:27:33

标签: php string variables compare

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

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

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

$myVars = $_GET['param'];
if ($myVars == NULL) {
//do code
}

5 个答案:

答案 0 :(得分: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
 }

供你参考,第一次启动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

答案 1 :(得分: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
}

为了检查$ _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
}

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

$myVar = $_GET['param'];

$ _ 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';
}

来源:

http://ca.php.net/isset

http://ca.php.net/array_key_exists

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

答案 2 :(得分:1)

如果您想检查是否设置了变量,请使用isset()

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

答案 3 :(得分:0)

要将变量与字符串进行比较,请使用:

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

要查看是否设置了变量,请使用isset(),如下所示:

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

答案 4 :(得分:0)

所有这些信息都列在PHP网站的“操作员”下

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