0
0

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 3 years have passed since last update.

配列のキーが連番でないときに、値を挿入する方法

Posted at

##配列のキーが連番じゃない
配列のキーが連番じゃなくて良い感じに値を入れてあげたい時。

$array = array(0=>'a', 1=>'b', 3=>'d');
$array += array_fill(0, max(array_keys($array)), 'c');
ksort($array);

実行結果

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
}

こんな風に自然な配列の形に整形できます。

$array += array_fill(0, max(array_keys($array)), '空です。');

実行結果

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(12) "空です。"
  [3]=>
  string(1) "d"
}

こんな風にすれば抜けていた配列の判別も簡単にできます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?