混淆空,isset,!空,!isset

时间:2011-10-04 11:39:53

标签: php

我有以下不能正常工作,因为$_GET['category']也可以等于0。

if ( empty( $_GET['category'] ) ){
    // do something
} else {
    // do something else
}

如何重写这个if语句来做3个不同的事情

  1. 如果$_GET['category']根本不存在
  2. ,请执行某些操作
  3. 如果$_GET['category'] == 0
  4. ,请执行某些操作
  5. 如果$_GET['category'] ==除“不存在”之外的其他内容并且为0,则执行某些操作。
  6. 我尝试了empty()!empty()isset()!isset()的不同组合,但我没有得到我追求的结果。我可能做错了组合......

6 个答案:

答案 0 :(得分:6)

这并不难:isset是您需要的方法。

if (!isset($_GET['category'])) {
    // category isn't set
} elseif ($_GET['category'] === '0') {
    // category is set to 0
} else {
    // category is set to something other than 0
}

请注意,我已经将完全相等性与字符串'0'进行了比较,因为GETPOST变量总是字符串(或偶尔是数组),并且在PHP首次接收它们时从不编号。

答案 1 :(得分:0)

if (!isset($_GET['category']))
{
    1. Do something if $_GET['category'] does not exist at all
}
elseif ($_GET['category'] == 0)
{
    2. Do something if $_GET['category'] == 0
}
elseif (isset($_GET['category']) && ($_GET['category'] != 0)
{
    3. Do something if $_GET['category'] == something other than "does not exist" and 0.
}

我的括号可能会稍微偏离某处,但希望这可以帮助你。

答案 2 :(得分:0)

此类案件有filter_input-function

答案 3 :(得分:0)

试试这个:

if (!isset($_GET['category'])) { // if variable not specified
}
elseif ($_GET['category'] == 0) { // variable is specified and zero
}
else { // variable is specified and not zero
}

答案 4 :(得分:0)

<?php

$bad_values = array(null, '', 'dirty word');

if(isset($_GET['xd']))
{
    if(in_array($_GET['xd'], $bad_values, true))
    {
        // bad, it was null, empty or something else you think is not ok 
    }
    else
    {
        // it's fine, now check whether you got the zero. do a string comparison 

        if($_GET['xd'] == '0')
        {
            // you got the zero, yell at the user
        }
        else
        {
            // you got something else, it might be fine, it might be spoofed. use referential integrity to enforce data integrity in your db
        }
    }
}
else
{
    // it wasn't even sent in the request, that falls under 1)
}

答案 5 :(得分:0)

确保设置上一页上正在执行name的元素的get属性,最好设置为与其id相同。 然后:

$category='';
if ( !isset( $_GET['category'] ) ){
    //1
} else {
    $category=$_GET['category'];
    //3
  if($category==0){
    //2
   }
}
相关问题