2

I need to replace the occurrences of count($variable) with !empty($variable) in IF statements so instead of

if(count($variable)){

}

I would like to use

if(!empty($variable)){

}

Is it safe to replace it always while ensuring that the result is always the same?

perpetual_dream
  • 1,046
  • 5
  • 18
  • 51
  • Does this answer your question? [How do I test if a variable does not equal either of two values?](https://stackoverflow.com/questions/6115801/how-do-i-test-if-a-variable-does-not-equal-either-of-two-values) – Labradorcode Nov 14 '19 at 09:41
  • https://stackoverflow.com/questions/6115801/how-do-i-test-if-a-variable-does-not-equal-either-of-two-values – Labradorcode Nov 14 '19 at 09:41
  • 1
    @Labradorcode OP asks whether `if(count($variable))` and `if(!empty($variable))` are interchangeable. I don't really see how the proposed duplicate answers that. (Not to mention that it's a different language.) – Ivar Nov 14 '19 at 09:46
  • `count('')` throws an error. Those are not the same. – StackSlave Nov 14 '19 at 10:07

2 Answers2

2

Test it:

foreach (['', null, 0, 0.0, '0', false, [], new stdClass, 'foo', 1, true, ['bar' => 'baz']] as $val) {
    var_dump($val, count($val), !empty($val));
    echo '-------------', PHP_EOL;
}

It differs for these cases:

string(0) ""
int(1)
bool(false)
-------------
int(0)
int(1)
bool(false)
-------------
float(0)
int(1)
bool(false)
-------------
string(1) "0"
int(1)
bool(false)
-------------
bool(false)
int(1)
bool(false)

Additionally, count will trigger an error for undefined variables. On PHP 7.2+, count also triggers an error for any non-Countable value (which is basically everything except array or classes that implement Countable).

So, if you can guarantee that your variable will always be an array, there's no difference. If your variable can be anything other than an array, including undefined, then you'll see anywhere between different results and errors triggered.

If you expect your variable to exist and to be an array/Countable, you should prefer count or just if ($variable) (since an empty array is falsy too) to get proper error messages if your value violates your expectations.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Worth mentioning that counting elements in an array to get boolean value is an overkill. An array can be used in boolean context without counting the elements. – Dharman Nov 18 '19 at 15:28
0

It's safe to replace IF your current count() uses do not rely on non standard cases, such as: count(false) (this will return 1)

If you are just counting arrays you should be good to go.

ikyuchukov
  • 565
  • 3
  • 12