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';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With