510
501

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 2014-05-28

#連想配列の追加

1. array_mergeを使う方法

array_merge
$hoge = array('key1'=>'value1');
$hoge = array_merge($hoge,array('key2'=>'value2'));

var_dump($hoge);
//=>array(2) { ["key1"]=> string(6) "value1" ["key2"]=> string(6) "value2" }

##2. +演算子を使う方法

+演算子
$hoge = array('key1'=>'value1');
$hoge = $hoge + array('key2'=>'value2');

var_dump($hoge);
//=>array(2) { ["key1"]=> string(6) "value1" ["key2"]=> string(6) "value2" }

もちろん、これでもOK

+演算子
$hoge = array('key1'=>'value1');
$hoge += array('key2'=>'value2');

var_dump($hoge);
//=>array(2) { ["key1"]=> string(6) "value1" ["key2"]=> string(6) "value2" }

##3. []を使う方法
要素ひとつだけなら[]も使える。

[]を使用
$hoge = array('key1'=>'value1');
$hoge['key2'] = 'value2';

var_dump($hoge);
//=>array(2) { ["key1"]=> string(6) "value1" ["key2"]=> string(6) "value2" }

※array_mergeと+演算子の違い

  • 同一キーの場合、array_mergeはvalue値を上書きして、+演算子はvalue値を上書きしない。
array_mergeと+演算子の違い(同一キーの場合)
$hoge_1 = array('key1'=>value1);
$hoge_2 = array('key1'=>value2);

var_dump(array_merge($hoge_1,$hoge_2));
//=>array(1) { ["key1"]=> string(6) "value2" }

var_dump($hoge_1 + $hoge_2);
//=>array(1) { ["key1"]=> string(6) "value1" }

  • キーが数値の場合、array_mergeはキーを採番し直す。+演算子はそのまま。
array_mergeと+演算子の違い(キーが数値の場合)
$hoge_1 = array(5=>value1);
$hoge_2 = array(8=>value2);

var_dump(array_merge($hoge_1,$hoge_2));
//=>array(2) { [0]=> string(6) "value1" [1]=> string(6) "value2" }

var_dump($hoge_1 + $hoge_2);
//=>array(2) { [5]=> string(6) "value1" [8]=> string(6) "value2" }

#配列の追加
##1 . array_pushを使う方法
array_push (配列,追加する要素[,追加する要素 ... ] )

array_push
$hoge = array('AAA','BBB');
array_push($hoge,'CCC','DDD');

var_dump($hoge);
//=>array(4) { [0]=> string(3) "AAA" [1]=> string(3) "BBB" [2]=> string(3) "CCC" [3]=> string(3) "DDD" }

##2 . []を使う方法

[]を使う
$hoge[] = 'AAA';
$hoge[] = 'BBB';

var_dump($hoge);
//=>array(2) { [0]=> string(3) "AAA" [1]=> string(3) "BBB" }

ちなみに、array_pushと[]では、[]を使った方が速度は早いらしい。

##3 . array_mergeを使う方法
PHPで配列はキーが数値の連想配列なので、array_mergeが使える。
また、array_mergeはキーが数値の場合、キーを採番し直すのでちょうど追加したような形になる。

array_push
$hoge = array('AAA','BBB');
$fuga = array_merge($hoge,array('CCC','DDD'));

var_dump($fuga);
//=>array(4) { [0]=> string(3) "AAA" [1]=> string(3) "BBB" [2]=> string(3) "CCC" [3]=> string(3) "DDD" }
510
501
2

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
510
501

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?