LoginSignup
0
0

More than 1 year has passed since last update.

PHP配列のキーを指定してみましょう!

Posted at

配列



以下の配列を var_dump と print_r で表示してみます。

index.php

<?php
$scores = [1, 2, 3];

var_dump($scores);
print_r($scores);



ターミナルに以下を実行します

~$ php index.php



var_dump は要素数と値の型を表示してくれて、

print_r は字下げして見やすくしてくれます。


~ $ php index.php
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
~ $ 



ではこの 0、 1、 2 のインデックス番号を好きなキーに置き換えてみましょう。

キーは数値や文字列に変える事が出来ます。

最初の配列に => を使ってキーを指定していきます。

index.php
<?php
$scores = [
  '1番目' => 1,
  '2番目' => 2,
  '3番目' => 3
];

var_dump($scores);
print_r($scores);



同じく var_dump と print_r で見てみましょう。

ターミナルに以下を実行します。

~$ php index.php



キーを指定する事が出来ました!

~ $ php index.php
array(3) {
  ["1番目"]=>
  int(1)
  ["2番目"]=>
  int(2)
  ["3番目"]=>
  int(3)
}
Array
(
    [1番目] => 1
    [2番目] => 2
    [3番目] => 3
)
~ $ 



キーを使って値にアクセスしてみましょう。

echo $scores [ '2番目' ] . PHP_EOL ; を追加します。

index.php
<?php
$scores = [
  '1番目' => 1,
  '2番目' => 2,
  '3番目' => 3
];

var_dump($scores);
print_r($scores);

echo $scores['2番目'] . PHP_EOL;    //$scoresの2番目を表示せよ



以下のターミナルを実行します。

~$ php index.php



$scoresの2番目が出力されました!

~ $ php index.php
array(3) {
  ["1番目"]=>
  int(1)
  ["2番目"]=>
  int(2)
  ["3番目"]=>
  int(3)
}
Array
(
    [1番目] => 1
    [2番目] => 2
    [3番目] => 3
)
2    
~ $ 
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