Skip to content

Instantly share code, notes, and snippets.

@dekokun
Created December 27, 2011 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dekokun/1523056 to your computer and use it in GitHub Desktop.
Save dekokun/1523056 to your computer and use it in GitHub Desktop.
そっかーPHPで配列をforeachにかけると格納順に処理されるのかー。
<?php
$a = array(0,1,2);
$a[5] = 5;
$a[4] = 4;
$a[3] = 3;
print_r($a);

foreach($a as $i=>$e){
    echo "[" . $i . "]=". $e . " ";
}
echo "\n";

出力は以下

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [5] => 5
    [4] => 4
    [3] => 3
)
[0]=0 [1]=1 [2]=2 [5]=5 [4]=4 [3]=3

なお、当方の環境は PHP 5.3.8 です

PHPにおいて配列は全て連想配列ということは知っていたがこういう順序で処理されるのか。知らんかった。どこかに仕様として記述されてるんですかね。

参考:
http://d.hatena.ne.jp/tanakahisateru/20081017/1224224745

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment