Last Updated: February 25, 2016
·
1.909K
· kanuj

Check a 1D array for emptiness

Checking a 1D array for empty values? Don't do a lengthy loop, do this instead:

if(strlen(implode('', $array)) == 0) 

7 Responses
Add your response

Why not just empty($array)?

over 1 year ago ·

Because sometimes arrays' keys might exist, but no value(s) for those keys. Technically, the array isn't empty, but you can't use any of those keys' values. Case in point, a form with 10 email address fields, whose field names are kept as email[]. When this form is submitted, the $_POST['email'] array will be non-empty, but won't have any values for any of its keys.

over 1 year ago ·

But why bother doing such a check when you still eventually have to loop through and check each individual fields.

If I fill 2 at random and leave the other 8 fields empty, you will still have to loop and get the 2 values.

over 1 year ago ·

Makes sense for a project I'm in right now, where the first validation has to be that the email field can't be empty. This acts as a first step of validation, and if it is, I simply return an error message. There will be a chance, atleast in our scenario where users will simply submit the form without filling in anything at all.

over 1 year ago ·

@kanuj Then why not do something like

if( !isset( $array['email'] ) || empty( $array['email'] ) )
over 1 year ago ·

@darkmantiscs Because in the scenario I just mentioned above it won't work. There's a form with multiple name and email rows, and the user can add more via JS. These fields are named like such: name[] and email[]. If the user submits an empty form, isset/empty won't validate a list of emails/names that don't have any data in them. The name/email arrays will have keys equal to the number of rows, but all of them will have empty values.

over 1 year ago ·
if (! array_filter($values, 'strlen'))

I think this line is more verbose, but I got to admit that it's a bit slower than @kanuj 's. Just a matter of preference I guess.

over 1 year ago ·