简体   繁体   中英

Check if Variables Are Set

What is the most efficient way of checking whether POST variables have been set or not?

Eg, I am collecting 10 variables from Page 1 , if they are set I would like to store that data on Page 2 . If not, I would like to assign ' not available '.

I am currently using if !empty , however it seems like there must be an easier/more efficient method, I'm quite new to php so any advice is appreciated.

Example code;

if (!empty($_POST["book"])) {
    $book= $_POST['book'];    
}else{  
    $book= 'not available';
}

if (!empty($_POST["author"])) {
    $author = $_POST['author'];    
}else{  
    $author= 'not available';
}

if (!empty($_POST["subtitle"])) {
    $subtitle= $_POST['subtitle'];   
}else{  
    $subtitle= 'not available';
}

etc...
etc...
etc...

Use a loop and variable-variables.

$fields = array('author', 'book', 'subtitle', ....);
foreach($fields as $field) {
   if (isset($_POST[$field])) {
      $$field = $_POST[$field]; // variable variable - ugly, but gets the job done
   } else {
      $$field = 'not available';
   }
}

Normally I use this helper function:

function defa($array, $key, $default){
    if(isset($array[$key])){
        return $array[$key];
    }else{
        return $default;
    }
}

Usage:

$book = defa($_POST, 'book', 'Not available');

Or, you can simplify if you are only using the $_POST array:

function post_defa($key, $default){
    if(isset($_POST[$key])){
        return $_POST[$key];
    }else{
        return $default;
    }
}

Usage:

$book = post_defa('book', 'Not available');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM