PHP: a short cut for isset and !empty?

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

    User-defined function, I 'm afraid. But they come out short enough. I have one lying around somewhere if you want to take a look, but it's really trivial as you can imagine.

    Update:

    Here's one I found:

    define('PARAM_INT', 0);
    define('PARAM_STR', 1);
    
    function get_param($name, $default = null, $type = PARAM_INT) {
        $value = $default;
    
        if (isset($_POST[$name])) {
            $value = $_POST[$name];
        }
        else if (isset($_GET[$name])) {
            $value = $_GET[$name];
        }
    
        switch($type) {
            case PARAM_INT:
                $value = (int)$value;
                break;
            case PARAM_STR:
                break;
            default:
                // error your heart out here
        }
        return $value;
    }
    

    Of course now all the cool kids do it with filter_var, but the idea is the same.

    0 讨论(0)
  • 2021-02-09 14:23

    I'm always making myself unpoular with that. But the best approach is to get over the micro optimization mantra and use the syntax construct which was devised for that @.

    Factually I'm lying. I'm all too often using isset() myself. (But at least I know it's not very bright.) And for new projects I'm now using object-oriented superglobals, which combine filtering and implicit isset tests into $_POST, $_GET, $_REQUEST wrappers. $_REQUEST->ascii["title"] or $_GET["raw"] don't bring up debug messages anymore.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-09 14:29

    empty($var) is an abbreviation for !( isset($var) && $var ).

    So !empty($_POST['...']) will be sufficient for your situation — the isset call you have currently is redundant.

    0 讨论(0)
  • 2021-02-09 14:33

    You can use a simple function

    function post_value_or($key, $default = NULL) {
        return isset($_POST[$key]) && !empty($_POST[$key]) ? $_POST[$key] : $default;
    }
    

    Then use:

    $pg_title = post_value_or('pg_title');
    // OR with a default
    $pg_title = post_value_or('pg_title', 'No Title');
    
    0 讨论(0)
提交回复
热议问题