isset()为NULL返回任何内容

时间:2017-11-30 13:54:49

标签: php laravel web-services if-statement

我已经写了这个PHP代码

//check if user has active plan and search keyword is not empty
    if (!empty($request['advertisername']) && ($userSubscriptionType == env('AMEMBER_STD_PLAN_CODE') || $userSubscriptionType == env('AMEMBER_PRE_PLAN_CODE'))) {
        $advertisername = 'LOWER(post_owner) like "%' . strtolower($request["advertisername"]) . '%"';
    } else {
        //if search keyword is null, means page is loaded for first time
        if (!isset($request['advertisername'])) {
            $advertisername = "true";
        } else {//if search keyword is not null, and user has not active plan
            $response->code = 400;
            $response->msg = "Permission issues";
            $response->data = "";
            return json_encode($response);
        }
    }

此处$request['advertisername']=null来自fronend。所以这个条件将是真的if (!isset($request['advertisername'])) {。但不幸的是,它总是会阻止其他阻碍。

如果我将$request['advertisername']保存在这样的变量中。然后这个条件if (!isset($advertiserName)) {变为真。

//check if user has active plan and search keyword is not empty
if (!empty($request['advertisername']) && ($userSubscriptionType == env('AMEMBER_STD_PLAN_CODE') || $userSubscriptionType == env('AMEMBER_PRE_PLAN_CODE'))) {
    $advertisername = 'LOWER(post_owner) like "%' . strtolower($request["advertisername"]) . '%"';
} else {
    //if search keyword is null, means page is loaded for first time
    $advertiserName=$request['advertisername'];
    if (!isset($advertiserName)) {
        $advertisername = "true";
    } else {//if search keyword is not null, and user has not active plan
        $response->code = 400;
        $response->msg = "Permission issues";
        $response->data = "";
        return json_encode($response);
    }
}

我通过var_dump()检查了条件。任何人都可以解释为什么会这样?

3 个答案:

答案 0 :(得分:1)

您可以改为使用array_key_exists():

if (!array_key_exists('advertisername', $request)) {

请注意isset()的PHP手册说:

isset — Determine if a variable is set and is not NULL

答案 1 :(得分:1)

您可以使用is_null()代替!isset()

答案 2 :(得分:1)

一个好方法是检查变量是否为空,因为它检查isset和null

eg if(!empty($your_variable) {    /** your code here **/   }