Jump to content

If statement executing when it shouldn't


ILMV

Recommended Posts

I cannot figure this one out, I have an array:

 

$errors=array();

 

When I go to check the count of the array:

 

if(count($errors>0)) {
    echo(count($errors));  // output is 0
}

 

...the condition executes! Even when I echo the count it says 0, how on earth is that happening? I didn't put >=, how is 0 > 0?

 

 

Cheers, Ben

Link to comment
https://forums.phpfreaks.com/topic/152805-if-statement-executing-when-it-shouldnt/
Share on other sites

Oh hang on...

 

  Quote
Caution

 

count() may return 0 for a variable that isn't set, but it may also return 0 for a variable that has been initialized with an empty array. Use isset() to test if a variable is set.

 

http://uk2.php.net/count

 

 

Maybe I will have not initialise it, and check if it has been set... seems slightly backwards to me :(

  Quote

Your "if" statement is wrong. It should be:

<?php
if(count($errors) > 0) {
?>

 

I prefer to use:

<?php
if (!empty($errors)) {
?>

 

Ken

 

Hello kenrbnsn!

 

Thanks for your suggestion, it works a whole lot better than count, also it looks neater.

 

Many Thanks!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.