Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php 5.3 Array Compatibility

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 write '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?

like image 987
Ruttyj Avatar asked Dec 07 '10 00:12

Ruttyj


2 Answers

This seems to identify the same, somewhat odd behavior.

http://www.tehuber.com/article.php?story=20090708165752413

like image 141
sberry Avatar answered Sep 25 '22 02:09

sberry


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.

like image 35
Matthew Avatar answered Sep 26 '22 02:09

Matthew