18

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';

7 Answers 7

38
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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 I don't know why anyone would want to do anything more complicated than this ...
+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).
@toomuchphp probably because if you are unfamiliar with Php's type juggling it's not immediately obvious.
7

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)

Comments

4

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)) { ... }

2 Comments

since PHP7.2, using count() will throw an error if called on a non-countable object. so if your $array is null, this approach will not work.
Another use case where this will not work: if you use an array name for an input field (like <input type="text" name="myInputField[]">) for several items, then, when the form is submitted without any inputs, the $_POST will include an array like this: myInputField = [0 =>"", 1=>"", etc.]. Using count(), will get a count of the nodes, but there won't be any values. So a mere count() may give you false indication that there are values to be processed.
3

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
}

Comments

0

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)) { ... }

Comments

0

The language construct isset(), is for testing to see if variables and array elements are set and not NULL. Using is_array() would tell you if the argument you supply to it is an array. Thus, I do not think using isset() or is_array() would give you the correct and desired result that you are seeking.

The code:

$signup_errors = array();

means that ...

is_array($signup_errors);

would return true. However, this does not mean that the Boolean language rules of PHP would evaluate....

if($signup_errors)
{
     //*Do something if $signup_errors evaluates to true*;
}

as true, unless some elements are added to it. When you did this,

$signup_errors['captcha'] = 'Please Enter the Correct Security Code';

you fulfilled the PHP language requirement for the array above to evaluate to true. Now, if for some reason you wanted, or needed, to use isset() on the array elements in the future, you could. But, the conditional statement above is enough for you this case.

Comments

0

I should add an obvious answer here. If you initialise your error array as an empty array. And later want to check if it is no longer an empty array:

<?php
$errors = [];

if($errors !== [])
{
    // We have errors.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.