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
Share on other sites

Oh hang on...

 

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 :(

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.