Re: Count empty array

From: Date: Thu, 21 Dec 2006 21:50:15 +0000
Subject: Re: Count empty array
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-246139@lists.php.net to get a copy of this message
Kevin Murphy wrote:
I'm wondering why this is. $data = ""; $array = explode(",",$data); $count = count($array); $count will = 1 $data = "Test"; $array = explode(",",$data); $count = count($array); $count will = 1 $data = "Test,Test"; $array = explode(",",$data); $count = count($array); $count will = 2 Why doesn't the first one give me an answer of 0 instead of 1. This:
var_dump(explode(',','')); Returns this: array(1) {
     [0]=>
     string(0) ""
} And oddly, This: var_dump(explode(',',NULL)); Returns this: array(1) {
     [0]=>
     string(0) ""
} That explains the count() result. It seems to me that the first case could go either way (The part of "" before the ',' is still ""), but I'm unable to think of a logical reason why the second doesn't return an empty array.
I know I could do a IF $data == "[empty]" and then not count if its empty and just set it to 0, but am wondering if there was a better way. $array = empty($data) ? array() : explode(',',$data); /* That what you're looking for? */
jon

« previous php.general (#246139) next »