Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a PHP array has any value set?

Tags:

arrays

php

I am working on a signup form, I am using PHP and on my processing part I run some code, if a submitted item fails I then add it to an errors array.

Below is a snip of the code, I am at the point where I need to find the best method to determine if I should trigger an error.

So if there is a value set in the error array then I need to redirect and do some other stuff.

I was thinking of using isset or else is_array but I don't think that is the answer since I set the array using **$signup_errors = array()** wouldn't this make the is_array be true?

Can anyone suggest a good way to do this?

//at the beginning I set the error array
$signup_errors = array();

// I then add items to the error array as needed like this...
$signup_errors['captcha'] = 'Please Enter the Correct Security Code';
like image 608
JasonDavis Avatar asked Sep 03 '09 02:09

JasonDavis


2 Answers

if ($signup_errors) {
  // there was an error
} else {
  // there wasn't
}

How does it work? When converting to boolean, an empty array converts to false. Every other array converts to true. From the PHP manual:

Converting to boolean

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.

See also Type Juggling.

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags
  • Every other value is considered TRUE (including any resource).

You could also use empty() as it has similar semantics.

like image 92
cletus Avatar answered Oct 03 '22 14:10

cletus


Use array_filter if you already have keys, but want to check for non-boolean evaluated values.

<?php
$errors = ['foo' => '', 'bar' => null];
var_dump(array_filter($errors));

$errors = ['foo' => 'Oops', 'bar' => null];
var_dump(array_filter($errors));

Output:

array(0) {
}
array(1) {
  ["foo"]=>
  string(4) "Oops"
}

Use:

<?php
if(array_filter($errors)) {
    // Has errors
}
like image 21
Progrock Avatar answered Oct 03 '22 13:10

Progrock