« 生 | メイン | PHP Idiosyncrasies #3 »

PHP Idiosyncrasies #2

"Pictures speak a thousand words", so let's jump straight into the code again:

  <?php
  $test_data = array(
    '1' => '1',
    'a' => 'a',
    '2' => '2',
    'b' => 'b',
    '00' => '00',
  );

  $test_data = array_flip($test_data);
  var_dump($test_data);

And the output:

  array(5) {
    [1]=>
    int(1)
    ["a"]=>
    string(1) "a"
    [2]=>
    int(2)
    ["b"]=>
    string(1) "b"
    ["00"]=>
    string(2) "00"
  }

Notice that numerical keys - actually only those matching ^(0|[1-9
][0-9]*)$
- have had there type changed from string to int.

And now for the important point:

  # Example 1
  var_dump(array_slice($test_data, 1));

  # Example 2
  array_shift($test_data);
  var_dump($test_data);

Both of the above examples produce:

  array(4) {
    ["a"]=>
    string(1) "a"
    [0]=>
    int(2)
    ["b"]=>
    string(1) "b"
    ["00"]=>
    string(2) "00"
  }

What's this? 2 => "b" has just been changed to 0 => "b"?
Yep, that's right. PHP will go ahead and renumber any integer keys when slicing and dicing arrays - even though it was given as a string in the first place.

トラックバック

このエントリーのトラックバックURL:
http://blog.linkthink.co.jp/mt/mt-tb.cgi/72

コメント (1)

リンクシンクが是非するの?

コメントを投稿

(いままで、ここでコメントしたことがないときは、コメントを表示する前にこのブログのオーナーの承認が必要になることがあります。承認されるまではコメントは表示されません。そのときはしばらく待ってください。)

BlogPet

リラックマ

About

2007年08月29日 18:59に投稿されたエントリーのページです。

ひとつ前の投稿は「」です。

次の投稿は「PHP Idiosyncrasies #3」です。

他にも多くのエントリーがあります。メインページアーカイブページも見てください。