检查 POST 变量是否已设置的最有效方法是什么?
例如,我正在从 Page 1 收集 10 个变量,如果设置了它们,我想将该数据存储在 Page 2 上。如果没有,我想分配“不可用”。
我目前正在使用 if !empty
,但似乎必须有一种更简单/更有效的方法,我对 php 还很陌生,所以欢迎任何建议。
示例代码;
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...
最佳答案
使用循环和可变变量。
$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';
}
}
关于php - 检查是否设置了变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27109828/