PHP: a short cut for isset and !empty?

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

    You can create a small function that can do this job for you simply.

    function sc_post_isset(...$args) {
        $exists = true;
    
        foreach($args as $arg) {
            if ( !isset($_POST[$arg])  || empty($_POST[$arg]) ) {
                $exists = false;
            }
        }
    
        return $exists;
    }
    

    Use,

    if(sc_post_isset('key')) {
         // it exists.
    }
    

    OR

    if(sc_post_isset('key1', 'key2', 'key3')) {
         // it exists.
    }
    

    It just simply check if all the provided keys exist within $_POST and not empty

提交回复
热议问题