php associative array values always set?
$test['test'] = 'test';
if(isset($test['test']['x']))
return $test['test']['x'];
This statement returns the first character of the string in $test['tes开发者_如何学JAVAt'] (in this case 't'), no matter what is specified as dimension 2.
I can't wrap my head around this behavior. I use isset() all the time. Please advise.
This happens because you're not indexing an array, you're indexing a string. Strings are not arrays in PHP. They happen to share a concept of indexes with arrays, but are really character sequences even though there is no distinct char data type in PHP.
In this case, since strings are only indexed numerically, 'x'
is being converted into an integer, which results in 0. So PHP is looking for $test['test'][0]
. Additionally $test
is only a single-dimensional array, assuming 'test'
is the only key inside.
Not really relevant to your question, but if you try something like this you should get 'e'
, because when converting '1x'
to an integer, PHP drops anything that isn't a digit and everything after it:
// This actually returns $test['test'][1]
return $test['test']['1x'];
If you're looking for a second dimension of the $test
array, $test['test']
itself needs to be an array. This will work as expected:
$test['test'] = array('x' => 'test');
if (isset($test['test']['x']))
return $test['test']['x'];
Of course, if your array potentially contains NULL
values, or you want to make sure you're checking an array, use array_key_exists()
instead of isset()
as sirlancelot suggests. It's sliiiiightly slower, but doesn't trip on NULL
values or other indexable types such as strings and objects.
Use array_key_exists
for testing array keys.
It's returning 't'
because all strings can be treated as arrays and 'x'
will evaluate to 0 which is the first letter/value in the variable.
精彩评论