PHP check if empty fields

I have a registration form with approximately 10 fields, and all of them should be filled out before processing, therefore, trying to avoid all these cases, if the checks that I came up with are a good method?

foreach($list as $items) { if(empty($items)) { $error[] = "All fields are required."; break; } } 

or should I do if (empty ($ field_1) || empty ($ field_2), etc. then output an error?

+4
source share
4 answers

Assuming your data comes from $_GET or $_POST , all data fields will be strings. This means that you must check in a call to one function :

 if (in_array('', $list, TRUE)) { $error[] = "All fields are required."; } 

This searches for strings that are exactly equal to the empty string. If you want to make comparisons free (more or less identical to the check empty() does), just delete the final TRUE .

EDIT Thinking about this, you don't need a rigorous comparison. I did this so that the valid value of the '0' field (which empty() did not allow), but it would also be allowed with free comparisons, since '0' != '' .

OTHER EDITING If you want to check that the length of the sting is more than two, you have to loop:

 foreach ($list as $item) { if (strlen($item) < 2) { $error[] = "All fields are required."; break; } } 

It will also "clear 0 ", assuming that by that you mean "do not allow the value 0 ". If you also want to disable '00' (or any other line that results in 0 ), you can change the if clause to this:

 if (strlen($item) < 2 || (!(int) $item)) { 
+3
source

this is normal. If you just want to show the message "All fields are required." without displaying a field in a space.

Otherwise, it will be more convenient for the user if you check and show which field is left empty.

+3
source

It's a good idea to put it in a loop, as you did, but note that this will not work even when the user enters 0 and passes a string containing only spaces, so you can do more efficient checks than empty()

+3
source

I would apply this with in_array validation.

 <?php $fields=array('name','age','yadayada','something_else'); foreach ($_POST as $key=>$value){ if(in_array($key,$fields) && $value!=''){ $$key=$value; }else{ $error[$key]='This field is required.'; } } ?> 
+2
source

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


All Articles