LoginSignup
3
0

More than 3 years have passed since last update.

配列に要素を追加

Posted at

配列に要素を追加

index.php
$text = [];
$array = ["hoge", "piyo"];

$text$arrayの要素を追加するという処理を書いていきます。

私が当初考えていた処理が次の処理です。

index.php
$text = [];
$array = ["hoge", "piyo"];
foreach ($array as $str) {
    $text[] = array_push($text, $str);
}

こちらを実行し$textvar_dump()すると

index.php
array(4) {
  [0]=>
  string(9) "hoge"
  [1]=>
  int(1)
  [2]=>
  string(9) "piyo"
  [3]=>
  int(3)
}

このような結果が返ってきます。
$textの[1]と[3]に何やら謎の要素が入ってしまっています。
実はarray_pushは返り値を返すのです。
返り値の値は、array_pushした段階での配列の要素数になります。

index.php
array(4) {
  [0]=>    // ---------------->①
  string(9) "hoge"
  [1]=>
  int(1)
  [2]=>    // ---------------->②
  string(9) "piyo"
  [3]=>
  int(3)
}

'hoge'を①、'piyo'を②とします。

array_push'hoge'を追加した時点では'hoge'のみが$text配列に入っているので、要素数は1となり、返り値として、1を返します。

次に'piyo'を追加した時点では、$text配列には'hoge'1'piyo'が入っており要素数は3となり返り値として3を返します。

こちらの処理を想定通りに動作させる為のコードとしては、

index.php
$text = [];
$array = ["hoge", "piyo"];
foreach ($array as $str) {
    array_push($text, $str);
}

または、

index.php
$text = [];
$array = ["hoge", "piyo"];
foreach ($array as $str) {
    $text[] += $str;
}

とすると良いです。

実行結果を確認すると、

index.php
array(2) {
  [0]=>
  string(4) "hoge"
  [1]=>
  string(4) "piyo"
}

きちんと表示されました。

以上、配列に要素を追加するでした。

ご閲覧ありがとうございました。

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