【问题标题】:Compare variables PHP比较变量 PHP
【发布时间】:2011-06-04 22:27:32
【问题描述】:

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

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

然后检查 url 中是否存在 $_GET[] 变量会是这样吗?

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

【问题讨论】:

  • 你的问题是什么?无论如何:第一个 sn-p 进行分配,我认为您想使用“==”而不是“=”。如果您的查询字符串中没有“参数”,第二个 sn-p 会给您一个警告(未定义的索引)。

标签: php string variables compare


【解决方案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
}

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

【讨论】:

  • 是的,你确实可以,如果 $_get 没有值,它不会被转移到 myVar,因此它将被视为 NULL 并且不被预处理器设置。
【解决方案2】:

为了比较字符串,我建议使用三等号运算符而不是双等号。

// 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,如果键存在但内容为空,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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

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

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

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

      【讨论】:

        【解决方案5】:

        所有这些信息都列在 PHP 网站上的 Operators 下

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-30
          • 2016-08-26
          相关资源
          最近更新 更多