简体   繁体   English

检查是否设置了变量

[英]Check if Variables Are Set

What is the most efficient way of checking whether POST variables have been set or not? 检查POST变量是否已设置的最有效方法是什么?

Eg, I am collecting 10 variables from Page 1 , if they are set I would like to store that data on Page 2 . 例如,我从第1页收集10个变量,如果它们已经设置,我想将这些数据存储在第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. 我目前正在使用if !empty ,但似乎必须有一个更简单/更有效的方法,我对php很新,所以任何建议都表示赞赏。

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: 或者,如果您只使用$ _POST数组,则可以简化:

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

Usage: 用法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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