tags:

views:

780

answers:

4

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';
+4  A: 

Perhaps empty()?

From Docs:

Return Values

Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
gnarf
+1  A: 

Check if...

if(count($array) > 0) { ... }

...if it is, then at least one key-value pair is set.

Alternatively, check if the array is not empty():

if(!empty($array)) { ... }
Amber
+6  A: 
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.

cletus
+1 I don't know why anyone would want to do anything more complicated than this ...
too much php
+1. Also good to note that **empty()** should be used if you cannot guarantee your variable has already been initialized (as in the case with $_POST data).
cballou
A: 

You could check on both the minimum and maximum values of the array, in this case you can have a large array filled with keys and empty values and you don't have to iterate through every key-value pair

if(!min($array) && !max($array)) { ... }
M Sandbergen