sayedsohail Posted July 31, 2007 Share Posted July 31, 2007 Hi everyone, I am using an array named $outdata, and just wish to know how to check if the array is empty. I am using this method if(empty($outdata)); i am not sure this is the right way to check if array is empty. Here is the code $outdata=array(); $outdata[]="Hello"; $outdata[]="Welcome"; if(empty($outdata)); { $outdata[]="You are not authorized"; } else { do something... } Quote Link to comment https://forums.phpfreaks.com/topic/62669-how-to-check-if-array-is-empty/ Share on other sites More sharing options...
mrjcfreak Posted July 31, 2007 Share Posted July 31, 2007 According to the manual; empty() will return true if the array has no items. (count($array) == 0) ? is probably the least confusing way of doing things Quote Link to comment https://forums.phpfreaks.com/topic/62669-how-to-check-if-array-is-empty/#findComment-311896 Share on other sites More sharing options...
sayedsohail Posted July 31, 2007 Author Share Posted July 31, 2007 Do u mean i should try something like this function isEmpty($array) { return (count(array_filter($array)) == 0) ? 1 : 0; } $may_not_empty = isEmpty($outdata); if($may_not_empty == 1) { do something } else { do something else } Quote Link to comment https://forums.phpfreaks.com/topic/62669-how-to-check-if-array-is-empty/#findComment-311905 Share on other sites More sharing options...
mrjcfreak Posted August 1, 2007 Share Posted August 1, 2007 Nope! use: if(count($array) == 0) { //The array is empty, it either doesn't exist or has no elements in it } else { The array exists and has things in it } or: if(isset($array)) { //The array exists, but might be empty } else { //The array does not exist at all, it was either never defined or unset/deleted } Depending on what exactly you want it to do. Choosing between them is what makes coding slightly more than following a recipe book. Quote Link to comment https://forums.phpfreaks.com/topic/62669-how-to-check-if-array-is-empty/#findComment-312641 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.