LoginSignup
0
0

More than 1 year has passed since last update.

PHPで配列の中の配列にアクセスしましょう!

Posted at

配列の中の配列



配列を、他の配列の中で使ってみます。

以下の配列があったとします。

$scores の配列の中に、 $numbers配列を入れています。


index.php
<?php
$numbers = [4, 5];

$scores = [
  1,
  2,
  3,
  $numbers,
  6,
];

print_r($scores);



ターミナルに以下を入力します。

~$ php index.php



配列の中に配列が入った状態で表示されます。

~ $ php index.php
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => Array
        (
            [0] => 4
            [1] => 5
        )

    [4] => 6
)
~ $ 



そのまま連続で入れ込みたい場合は、

配列の前に 「 ... 」 をつけます。

index.php
<?php
$numbers = [4, 5];

$scores = [
  1,
  2,
  3,
  ...$numbers,
  6,
];

print_r($scores);



ターミナルで以下を実行すると...

~$ php index.php



連続で表示されました!

~ $ php index.php
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
~ $ 



配列の要素にアクセスしてみます。

以下の配列があったとします。

$numbers 配列の中にさらに配列を入れています。

echo $scores [ 5 ] [ 1 ] で配列を呼び出します。


index.php
<?php
$numbers = [
  4,
  5,
  [10, 20],
  ];

$scores = [
  1,
  2,
  3,
  ...$numbers,
  6,
];

echo $scores[5][1] . PHP_EOL;



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

~$ php index.php



$scores の5番目の配列の中の1番目が取り出されました!

~ $ php index.php
20
~ $ 
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