How do I determine if an array is empty in PHP?
Asked Answered
S

2

8

I want to check that an array has no values or that the values in the array are empty. Can someone explain how to do this?

Silvern answered 13/4, 2011 at 13:1 Comment(2)
What do you mean by "array values is empty"? Useful functions/constructs: is_array, count, empty, isset. It all depends on what exactly you're trying to test.Huarache
here is an array with no values only keys .i used count and empty but those functions are saying array has values .Array ( [delegate_title] => [delegate_firstname] => [delegate_lastname] => [delegate_jobtitle] => [delegate_email] => [delegate_phone] => [is_bringing_own_laptop] => )Silvern
H
21

Someday I've learned very smart solution here on SO

if(!array_filter($array)) {
  //array contains only empty values
}

or even smarter one (if applicable):

if(!array_filter($array,'trim')) {
  //array contains only empty values
}
Hindsight answered 13/4, 2011 at 13:12 Comment(5)
@Vinay it seems empty() is better anywayHindsight
but empty gives me that array has valuesSilvern
@Vinay what PHP version you're using?Hindsight
in local machine php 5 and in server its php 4Silvern
array_filter is really handy! never used it before today, but it solves my problem! thank you!Rodd
F
11

You want the empty() function, here's the documentation of the empty function http://php.net/manual/en/function.empty.php

Fluorene answered 13/4, 2011 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.