Function to check that all elements of a variable array are null

Asked

Viewed 565 times

2

Suppose I have one array in which each element of this array is a variable that stores a string within it.

Example:

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

I’d like the program to identify if all the variables in that array sane null, then perform another routine.

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

I tried to run that way, unsuccessfully:

if(!empty($error)){
    $data["error"] = $error;
}else{
    //executa outra rotina
}
  • And why do you need to know if they’re all null?

  • My goal is: if there is no error occurrence (all variables in this array are null), it goes down to the step that makes the inclusion of registered information (capturing inputs from my registration screen) in the database. I’m wearing a Restful pattern.

1 answer

4


Walk the array and check with is_null() if the value is null. If it is not already you can end the execution since one is not null enough to return false. Only if it goes through all the array without finding a non-null value it returns 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;
}

I put in the Github for future reference.

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

  • That’s the idea. I’ll test and give the feedback. = ) Anyway, I marked it as the best response. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.