3

An empty array in PHP is considered falsey. That means the following will not print anything as the array is empty.

<?php
$myArray = array()

if ( $myArray ) {
  print "My Array is NOT empty";
}

What is considered better practice in this case when determining if there are elements in the array:

  1. To use if ( !empty( $myArray ) )
  2. To use if ( myArray )

Please note: this question is not about subjectivity. I don't care what my team mate thinks. I care about best practices in the industry.

Ally
  • 147
  • 1
  • 5
  • Possible duplicate of [How would you know if you've written readable and easily maintainable code?](https://softwareengineering.stackexchange.com/questions/141005/how-would-you-know-if-youve-written-readable-and-easily-maintainable-code) – gnat May 02 '17 at 11:15
  • @gnat This is not the same question. Please don't downvote something if you're basing it on subjectivity alone. It's about best practices in the industry not because my team mate says so. – Ally May 02 '17 at 11:19
  • 5
    https://softwareengineering.meta.stackexchange.com/a/8222/1352 – Jörg W Mittag May 02 '17 at 11:47
  • A best practice in the industry is Software Development as a Team Sport - https://www.thoughtworks.com/radar#software-development-as-a-team-sport . You need to care what youre team mate thinks. – bdsl Jan 28 '20 at 10:59

5 Answers5

6

If the intent of your condition is to check that the array contains 0 elements, using count($array) === 0 is the best and most readable solution.

Thijs Riezebeek
  • 336
  • 1
  • 6
  • Actually, you'll never get an error, as `count()` is defined for all types, it simply returns `1` for anything other than an array. However it will return `0` for an unset variable (which would raise a Notice), or for `null`: https://3v4l.org/7lEGR Whether this particular set of cases is more or less useful than other "empty"/"falsey" values depends on the situation. – IMSoP May 03 '17 at 13:33
  • 2
    Of course. I forgot the most important php rule. Never make assumptions about the behavior of built-in functions. – Thijs Riezebeek May 03 '17 at 14:18
  • Well, more straight-forwardly, "don't expect built-in functions to complain about types". Throwing an error for the wrong type is very rare, most functions just try to give a reasonable answer. In this case, the function simply asks "how many things are in this variable?" - if it's `null`, then there are 0 things; if it's a scalar or non-countable object, there is 1 thing; if it's an array or collection object implementing [Countable](http://php.net/Countable), then it looks how many things are in the list / collection. Another clue that the name is `count` not `array_count`. – IMSoP May 03 '17 at 14:52
  • I understand the importance of readability and the hate for `empty()`, but it should be mentioned that counting (= iterating the whole array) is **much** slower and could even result in memory issues when working with huge arrays and/or being careless with the memory in general. So, always be aware of what you count! :) – Marcello Mönkemeyer Jul 09 '18 at 16:31
  • @MarcelloMönkemeyer, actually, the C struct representing the array in the PHP core keeps track of the length of the array, so `count()` on a native array will only cause that `int` value to be returned. This makes the check very inexpensive. – Thijs Riezebeek Jul 10 '18 at 17:16
  • @ThijsRiezebeek Not for PHP 5 though, which is still supported and widely used. But you're absolutely right about newer versions using hash tables - I wasn't aware of that when I wrote the comment. Still living in the past sometimes. ^^ – Marcello Mönkemeyer Jul 12 '18 at 15:38
  • @MarcelloMönkemeyer Are you sure PHP 5 doesn't? I just benchmarked counting an array with 30 million elements and `count` took between 5-10 microseconds. – dirtside Jul 17 '18 at 17:26
0

I'd say it depends on the "typical" audience who would be reading the code.

  1. If they are likely to be beginners, less familiar with PHP, or coming from a more verbose language (like Java), then they longer, more explicit if ( !empty( $myArray ) ) would be more clear.

  2. If they are moderately experienced with PHP, C, JavaScript, etc. then the terser, more idiomatic if ( $myArray ) would be my preference.

user949300
  • 8,679
  • 2
  • 26
  • 35
0

loose type is one of problems of PHP, but also it gives good developers more flexibility.

If you already defined $myArray = array(); Then you can just use if ($myArray), because you already know it is an array, and also the name tells you it is an array. falsy case would happen only when $myArray is empty.

But, you don't need to specify $myArray because there is a count() function, check if it is empty Countable. It will throw a warning when you pass a string of anything not countable. (above PHP7.2)

No matter what you prefer, there is no point to do if (!empty($myArray)) because you are coding in PHP. You need to take advantage of falsy values, not against it.

0

This is the correct way in PHP; please use the below format:

$array = array(......);  

  if(!empty($myArray) && count($myArray) > 0){

        echo 'array is not empty';

}
Glorfindel
  • 3,137
  • 6
  • 25
  • 33
0

if you want to retrieve data from array at that time if ( $myArray ) is simplest way.

if ( $myArray ) is falsy case this can happen when array does not have any element.

( $myArray ) is not applicable to associative arrays.

If you want to check that array is empty or not at that time you can use if ( empty( $myArray ) ) beacuase it provide better performance for all type of array .so if ( empty( $myArray ) ) is better practice for checking empty array.

you can consider following result:

Contents  \method |    count     |    empty     
------------------|--------------|--------------|
            Empty |/* 1.213138 */|/* 1.070011 */|
          Uniform |/* 1.206680 */|   1.047339   |
          Integer |/* 1.209668 */|/* 1.079858 */|
           String |/* 1.242137 */|   1.049148   |
            Mixed |/* 1.229072 */|/* 1.068569 */|
      Associative |/* 1.206311 */|   1.053642   |
------------------|--------------|--------------|
            Total |/* 7.307005 */|   6.368568   |
AjayGohil
  • 231
  • 1
  • 7