Home > Net >  Add to array if not empty returned
Add to array if not empty returned

Time:09-28

I use a function to check if multiple inputs are empty or not.

Here is the function in functions.php:

function isEmpty($input){
    if(empty($input)){
        return "Input required";
    }
}

function checkLenth($input){
    if(strlen($input) < 3){
        return "Input length must be more than 3";
    }
}

Then I call the function in a differnet file for all inputs:

isEmpty($_POST['name']);
isEmpty($_POST['email']);

checkLength($_POST['name']);

I want to add the messages to an array, So I do the following:

$errors = array();

$errors[] = isEmpty($_POST['name']);
$errors[] = isEmpty($_POST['email']);

$errors[] = checkLength($_POST['email']);

This works fine if these fields are empty. But if not the array contains empty strings.

How to avoid this so that the array only contains the messages and if no errors don't add to the array?

CodePudding user response:

You can first check if the result is empty. $errors = array();

if ($info = isEmpty($_POST['name'])) {
     $errors[] = $info;
}

if ($info = isEmpty($_POST['email'])) {
     $errors[] = $info;
}

CodePudding user response:

try this solution

// $errors is global 
$errors = array();

isEmpty($_POST['name']);
isEmpty($_POST['email']);

function isEmpty($input){
    if(empty($input)){
        global $errors;
        $errors[] = "Input required";
    }
}
  •  Tags:  
  • php
  • Related