Check if variables are set

What is the most efficient way to check if POST variables have been set?

For example, I collect 10 variables from Page 1 , if they are set, I would like to save this data on Page 2 . If not, I would designate "inaccessible."

I am currently using if !empty , but it seems like there should be a simpler / more efficient method, I'm pretty new to php, so any advice is welcome.

Code example;

 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... 
+6
source share
2 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'; } } 
+9
source

I usually use this helper function:

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

Using:

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

Or you can simplify if you use the $ _POST array:

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

Using:

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

Source: https://habr.com/ru/post/978632/


All Articles