In php 5.3 the way arrays are handled have changed.
Example array:
<?php $a = array ('foo' => 1, 'bar' => 2, 'foo' => 3); ?>
use to over wr开发者_如何学运维ite 'foo' with the last one in the array to give:
array(
'foo' => 3,
'bar' => 2
)
now in 5.3 it returns
array(
'foo' => 1,
'bar' => 2
)
I am testing on a php v5.2.11 so i can not test this my self this example is from the php.net website: http://php.net/manual/en/language.types.array.php and search the page for 5.3
would the method of setting values via
<?php
$a['foo'] = 1;
$a['bar'] = 2;
$a['foo'] = 3;
?>
provide a backward compatible patch for this issue? are there any other things to watch out for when dealing with arrays in the new version of php?
This seems to identify the same, somewhat odd behavior.
http://www.tehuber.com/article.php?story=20090708165752413
From the manual:
Note that when two identical index are defined, the last overwrite the first.
So unless you've somehow triggered a PHP bug (unlikely), then there's something else going on that you're missing.
And to answer your question, yes, overwriting keys via the assignment operator works. However, before you start changing code around, I'd check to make sure the problem is what you currently think, because the manual does directly claim that the latter keys will overwrite the former ones.
Update: @sberry2A's link does reveal a place where PHP 5.3 is buggy (i.e., doesn't do what the manual says).
class Foo
{
const A = 1;
const B = 1;
public static $bar = array(self::A => 1, self::B => 2);
}
One would expect that the value of Foo::$bar[1]
is 2
, but it's still 1
. However, the following works properly:
class Foo
{
const A = 1;
const B = 1;
public static function bar()
{
return array(self::A => 1, self::B => 2);
}
}
So it's only that specific case of static property arrays indexed by different constants that have the same value. That's the only way in PHP 5.3.3 that I can trigger the behavior, but perhaps there are other ways to as well... obviously a certain behavior cannot be relied upon.
I think you should use unique keys for the array.
<?php $a = array ('foo' => 1, 'bar' => 2); ?>
Then update the value of foo.
<?php $a['foo'] = 3; ?>
精彩评论