isset() returning nothing for NULL



我已经写了此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)) {变为true。

//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()检查了条件。任何人都可以解释为什么会发生?

您可以使用is_null()而不是!isset()

您可以使用array_key_exists()而不是:

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

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

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

一种很好的方法是检查变量是否不为空,因为它同时检查了isset和null

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

相关内容

  • 没有找到相关文章

最新更新