Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Variables Are Set

Tags:

php

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...
like image 748
jonboy Avatar asked Nov 24 '14 16:11

jonboy


1 Answers

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';
   }
}
like image 55
Marc B Avatar answered Nov 11 '22 13:11

Marc B