5
5

More than 5 years have passed since last update.

phpで「配列」〜 前編

Posted at

複数の項目をカンマで区切って変数に格納出来る

1つの変数に複数の値を格納出来るのが「配列」です。

① array構文

例えば、複数の登場人物を$azumangaという変数に格納して、何番目なのかを指定すれば名前を参照出来ます。

この配列を作成するときに使うのがarrayという命令です。

とりあえずあずまんがのいつもの6人組でやってみましょう

<html>
<head>
</head>
<body>

<?php  
$azumanga = array(
    "ちよ",
    "おおさか",
    "かぐら",
    "さかき",
    "よみ",
    "とも",
);

echo $azumanga[4];

?>

</body>

</html>

php00010.png

② 連想配列

①の配列では、配列要素の位置を示すインデックスは0から始まる数値ですが、もう少し「取り出ししやすい」インデックスを持つ配列を作成する事も出来ます。

これが「連想配列」と呼ばれる配列で中身を連想出来る様なインデックスを持つ配列です。取り出す項目のインデックスを指定しやすいので便利です。

連想配列の作り方の1つとして以下の様に書く事が出来ます。


<html>
<head>
</head>
<body>

<?php
$azumanga = array (
"chiyo" => "ちよ",
"osaka" => "おおさか",
"kagura" => "かぐら",
"yomi" => "よみ",
"tomo" => "とも",
"sakaki" => "さかき",
);

echo $azumanga["kagura"];
?> 

</body>

</html>

また、後から「かおりん」を付け足したかったら

以下の方法で付け足せば、「かおりん」も追加されて表示出来ます。


<html>
<head>
</head>
<body>

<?php
$azumanga = array (
"chiyo" => "ちよ",
"osaka" => "おおさか",
"kagura" => "かぐら",
"yomi" => "よみ",
"tomo" => "とも",
"sakaki" => "さかき",
);

$azumanga["kaorin"]  = "かおりん";

echo $azumanga["kaorin"];

?>

</body>

</html>

↓実行結果

php00011.png

5
5
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
5
5