How do I find out if any array is empty?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KeredDrahcir
    Contributor
    • Nov 2009
    • 426

    #1

    How do I find out if any array is empty?

    I'm trying the run a function that only executes if an array is empty.
    If the array is empty is technically has one element with the value of ''.

    Code:
    if(array_filter($array))
    The above code should tell me if the array has one or more non-empty elements and it works. However although it works, I get this message.

    Warning: array_filter() [function.array-filter]: The first argument should be an array in /my server/my site /public_html/my file.php on line 40

    If there a solution to this please?
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    #2
    There's several ways to do this, it all depends on what you array actually looks like. it would have helped if you printed a few example arrays. For example if the array has multiple keys but all with empty-string values, does that count as empty?

    Code:
    // check if first element is empty. 
    
    if($myarr[0]) ...
    
    if(strlen($myarr[0]) > 0) ...
    
    $foo = array("key1" => '', "key2" => ' ', "key3" => '   ');
    
    $bar = trim(implode($foo));
    if(empty($bar)) ...
    you should definitely have a look at php's empty function at php.net/empty

    Cheers Mate,


    Dan

    Comment

    • KeredDrahcir
      Contributor
      • Nov 2009
      • 426

      #3
      Those suggestions look realy helpful. When I next get back to that probject I'll try them out and let you know.
      Thanks.

      Comment

      • KeredDrahcir
        Contributor
        • Nov 2009
        • 426

        #4
        None of those worked.
        I counted the araay and it gave me one, if there was one item there and one (presumably) empty item there, but that item didn't seem to be empty. Although I had a look at the result, it gave me nothing.

        Comment

        • zorgi
          Recognized Expert Contributor
          • Mar 2008
          • 431

          #5
          array sample and some code of what you done so far would be very helpful here.

          Comment

          Working...