In this tutorial we will create a function to check if a field is empty in either a string or an array. So this could be used to do a simple check on if a form field is left blank. I will show you an example on how to use it to check if a form field is empty.
So heres the function
function empty_check($var){ // Start Function if(is_array($var)){ // Determine if $var is an array or not foreach($var as $key => $value){ // If it is an array go through the array and assign to $key and $value $value = trim($value); // Remove any whitespace from the start and end of the value if(empty($value)){ // Check if its empty or not $empty[] = $key; // If its empty put the name of the field thats empty in $empty array. } } }else{ // If it isnt in an array $var = trim($var); // Remove any whitespace from the start and end of the value if(empty($var)){ // Check if its empty or not $empty[] = $var; // If its empty put the value into the $empty array. } } return $empty; // Return $empty. }
So now we have the function I will show you an example on how you can use this.
<?php if($_POST['submit']){ $empty = empty_check($_POST); if($empty){ echo "You have left the following fields empty<br />"; foreach($empty as $value){ echo $value . ", "; } }else{ echo "All fields are filled in."; } } ?> <form method="post" action=""> <input type="text" name="first_name" /> <input type="text" name="last_name" /> <input type="submit" value="Submit Button" name="submit" /> </form>