PHP: a short cut for isset and !empty?

后端 未结 11 2085
余生分开走
余生分开走 2021-02-09 13:45

I wonder if there any better ideas to solve the problem below,

I have a form with a number of input fields, such as,



        
11条回答
  •  青春惊慌失措
    2021-02-09 14:15

    +1 for array_merge() but I think that nevertheless short form for:

    if (isset($_POST['some_var']) and !empty($_POST['some_var'])) $some_var = $_POST['some_var'];
    else $some_var = NULL;
    

    should be:

    $some_var = $_POST['some_var'] ? $_POST['some_var'] : NULL;
    

    yes, it causes "undefined index" notice, but it checks for both existance and emptiness

    EDIT: and returns NULL of course, as OP asked.

    During a small research, I've found an interesting "Control Flow Function" for this case, I've never used before: NULLIF()

    So you can perform this task without PHP. Just wrap all variables in it:

    NULLIF('".$_REQUEST['some_var']."', '')
    

    in your query instead of '".$_REQUEST['some_var']."'

    If variable is empty or doesn't exist it will be NULLIF('', '') as far as '' == '' it will return NULL. Otherwise it will return first arg == your variable.

提交回复
热议问题