ILMV Posted April 6, 2009 Share Posted April 6, 2009 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 More sharing options...
mrMarcus Posted April 6, 2009 Share Posted April 6, 2009 print_r($errors); you'll probably notice that there's an empty value in the array with a key of 0, right? Link to comment https://forums.phpfreaks.com/topic/152805-if-statement-executing-when-it-shouldnt/#findComment-802442 Share on other sites More sharing options...
ILMV Posted April 6, 2009 Author Share Posted April 6, 2009 Hey Marcus No, I have print_r'd it, and it returns an empty array, not keys or values... Array ( ) Link to comment https://forums.phpfreaks.com/topic/152805-if-statement-executing-when-it-shouldnt/#findComment-802445 Share on other sites More sharing options...
kenrbnsn Posted April 6, 2009 Share Posted April 6, 2009 Your "if" statement is wrong. It should be: <?php if(count($errors) > 0) { ?> I prefer to use: <?php if (!empty($errors)) { ?> Ken Link to comment https://forums.phpfreaks.com/topic/152805-if-statement-executing-when-it-shouldnt/#findComment-802448 Share on other sites More sharing options...
ILMV Posted April 6, 2009 Author Share Posted April 6, 2009 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 Link to comment https://forums.phpfreaks.com/topic/152805-if-statement-executing-when-it-shouldnt/#findComment-802450 Share on other sites More sharing options...
ILMV Posted April 6, 2009 Author Share Posted April 6, 2009 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! Link to comment https://forums.phpfreaks.com/topic/152805-if-statement-executing-when-it-shouldnt/#findComment-802455 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.