10

This is mostly superficial but what's the best (faster performing, not personal preference or readability) way to check if an array is empty:

  1. count($arr) == 0
  2. empty($arr)
  3. $arr === array()
  4. Other?

My Guess is that

  1. Iterates as far as possible then returns
  2. Simply performs 1 after checking if the variable is an array
  3. Seems like it should be slow as it has to construct a new object to compare with

But that doesn't account for any compile time optimizations that it performs here.

Disclaimer

I'm not about to go through my code base changes all instances to the fastest possible method so please don't remind me it's micro optimzation. This is simple curiosity.

Community
  • 1
  • 1
Paystey
  • 3,237
  • 2
  • 16
  • 32
  • I'm guessing there's very little difference in most cases. Personally though (and without testing) I suspect empty() is a tiny bit faster. The count() and finally the comparison. – Dave Mar 04 '13 at 13:24
  • 1
    http://stackoverflow.com/questions/4014327/best-way-to-check-a-empty-array?rq=1 – l2aelba Mar 04 '13 at 13:24
  • There is another topic : http://stackoverflow.com/questions/2216110/checking-for-empty-arrays-count-vs-empty – JoDev Mar 04 '13 at 13:30
  • 3
    Simple `!$arr` is fastest, `empty()` is second, `=== array()` is third, `count` is distant fourth (5.4.3) But you're right, it's nothing more than micro-op. – raina77ow Mar 04 '13 at 13:42
  • Whatever you do, don't use `count()` from benchmarks I've done in the past is slow as hell. – TCB13 Apr 28 '14 at 10:20
  • I disagree with the moderators. Constructive Question. empty() and !$ary are the fastest. php 5.4 --- question is closed, so here are the benchmarks -- MIN: time ratio (1000x), fastest times (least scheduler interference) Array ( [3."global $a; (empty($a))"] => 1.00x (3.886222839355469E-5) [2."global $a; (!$a)"] => 1.06x (4.100799560546875E-5) [4."global $a; (!isset($a[0]))"] => 1.29x (5.006790161132812E-5) [1."global $a; ($a === array())"] => 1.44x (5.602836608886719E-5) [5."global $a; (count($a))"] => 4.89x (0.0001900196075439453) ) – Beracah Nov 07 '16 at 22:35

2 Answers2

2
    if(empty($arr))
    echo "Empty";
    else
    echo "Ok..!";

This is the fastest and secure way to check an array empty or not

ajay
  • 1,490
  • 2
  • 12
  • 16
1

an empty array is:

    $emptyArray = array();

check its empty:

    if( empty( $emptyArray ) ){

         echo 'array is empty';

    }

if array is not empty:

    $notEmptyArray = array( 'item' );

check its not empty:

    if( !empty( $notEmptyArray ) ){

         echo 'array not empty';

    }

there are other ways of doing it, but the empty function built for this sort of thing.

Nahser Bakht
  • 820
  • 2
  • 12
  • 26