1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでインデックスを使って配列を組み立てた際の動作

Last updated at Posted at 2018-05-29

自分が思っていたのと違う動作をしていたのでメモ

$list = [];
$list[2] = 'c';
$list[0] = 'a';
$list[1] = 'b';

foreach ($list as $index => $element)
{
    var_dump($index, $element);
}
int(2)
string(1) "c"
int(0)
string(1) "a"
int(1)
string(1) "b"

あれ?こんな動作だっけ
ソートされないのはJavaScriptでも同じだったけ?
と思ったので試してみました。

var list = [];
list[2] = "c";
list[0] = "a";
list[1] = "b";

list.forEach(function(element, index) {
  console.log(index, element);
});
0 "a"
1 "b"
2 "c"

動作違うのかー。

PHPでは組み立てた後にksortを使わないといけない。PHPの配列は連想配列と言われるけどインデックスでも文字列キーと同じような扱いなのかな。

$list = [];
$list[2] = 'c';
$list[0] = 'a';
$list[1] = 'b';
ksort($list);

foreach ($list as $index => $element)
{
    var_dump($index, $element);
}
int(0)
string(1) "a"
int(1)
string(1) "b"
int(2)
string(1) "c"
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?