开发者

array size > 0 although no key is set

short question.

given the following example:

$arr = array();
$arr[0] = false ?: NULL;
var_dump($arr[0]);
var_dump($arr[1]);
var_dump(isset($arr[0]));
var_dump(isset($arr[1]));
var_dump(count($arr));

the resulting output is:

NULL 
NULL 
bool(false) 
bool(false) 
int(1)

why does the resulting array have a size of 1 instead of 0 and is there any way to prevent this fro开发者_如何学运维m happening when using the ternary operator? is it a bug or intended behaviour?

btw, I'm running php 5.3.3-7, but can't test it on a different version at the moment.


isset() returns false if the variable is not set, or the variable is equal to NULL. In this case, $arr[0] is explicitly set to NULL. This is semantically different to actually unset()ing it: the variable is still set, it's just set to an empty value.

In short: working as intended. It's an unfortunate side effect of different functions doing slightly different things.

As a sidenote, using foreach on this array will actually return the 0 => NULL key/value pair as well, as you might expect from the value returned by count().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜