PHP: a short cut for isset and !empty?

后端 未结 11 2226
余生分开走
余生分开走 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:25

    isset && !empty is redundant. The empty language construct is basically shorthand for !isset($foo) || !$foo, with !empty being equivalent to isset($foo) && $foo. So you can shorten your code by leaving out the isset check.

    A much simpler way is:

    $values = array('pg_title' => null, 'pg_subtitle' => null, …);
    $values = array_merge($values, $_POST);
    
    // use $values['pg_title'] etc.
    

    If you don't want your default null values to be overwritten by falsey values, e.g. '', you can do something like this:

    $values = array_merge($values, array_filter($_POST));
    

    Just be aware that '0' is falsey as well.

提交回复
热议问题