LoginSignup
0
0

More than 3 years have passed since last update.

PHP 変数の後ろに[]をつける場合と付けない場合の違い

Last updated at Posted at 2020-09-28

変数の後ろに[]をつける挙動を知らなかったのでメモ

// index.php
$errors = [];

$erros = 3;
var_dump($errors);
// int(3)

これだと配列が上書きされ、$errorsが文字列になってしまう。

// index2.php
$errors[] = 3; 
$errors[] = 2;
$errors[] = 'a';
var_dump($errors);

array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  string(1) "a"
}

変数の後ろに[]をつけることで、配列の中身に値を代入できる。

// index3.php
$errors = [];
$errors['hoge'] = 3;
var_dump($errors);
// array(1) {
//  ["hoge"]=>
//  int(3)
// }

hogeがキーに3がvalueになる。

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