Function to check if all elements of an array of variables are null

2

Suppose I have an array where each element of this array is a variable that stores a string inside it.

Example:

error{
   [nome] : null;
   [sobrenome] : "sobrenome inválido";
   [estado] : null; }

I would like the program to identify if all the variables in this array are null , then run another routine.

error{
   [nome] : null;
   [sobrenome] : null;
   [estado] : null; }

I tried to run this way, without success:

if(!empty($error)){
    $data["error"] = $error;
}else{
    //executa outra rotina
}
    
asked by anonymous 28.09.2018 / 15:52

1 answer

4

Scroll through the array and check with isnull() if the value is null. If it is not already can terminate the execution since a non sufficient one being null to returns false. Only if it traverses all the array without finding a non-null value does it return true. Then just use this function in your if .

function AllNull($error) {
    foreach ($error as $key => $value) if (!is_null( $value)) return false;
    return true;
}

But depending on what you need it may be that the best solution is another one composing it in another way.

    
28.09.2018 / 17:10