Shortcut to check if all $ _POST fields are filled in php

I know I can check if the superglobal $ _POST is empty or not using

empty / isset 

However, I have many fields here. Is there a shortcut to check if all fields are filled? Instead of doing

 if (!empty($_POST['a']) || !empty($_POST['b']) || !empty($_POST['c']) || !empty($_POST['d']).... ad nauseum) 

Thanks in advance!

+5
source share
4 answers

You can use array_filter and compare both accounts

 if(count(array_filter($_POST))!=count($_POST)){ echo "Something is empty"; } 
+7
source

You can iterate over the $ _POST variable.

For instance:

 $messages=array(); foreach($_POST as $key => $value){ if(empty($value)) $messages[] = "Hey you forgot to fill this field: $key"; } print_r($messages); 
+4
source

Here, the function I just created can help.

if any of the arguments you pass is empty, it returns false. if it does not return true.

 function multi_empty() { foreach(func_get_args() as $value) { if (!isset($value) || empty($value)) return false; } return true; } 

Example

 multi_empty("hello","world",1234); //Returns true multi_empty("hello","world",'',1234); //Returns false multi_empty("hello","world",1234,$notset,"test","any amount of arguments"); //Returns false 
+2
source

You can use the foreach() to check each $_POST value:

 foreach ($_POST as $val) { if(empty($val)) echo 'You have not filled up all the inputs'; } 
+2
source

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


All Articles