LoginSignup
3
0

More than 5 years have passed since last update.

ヒアドキュメントと連想配列

Last updated at Posted at 2018-09-14

こんなサンプルコードを書いてみた。

<?php

$size = array(
    'height' => 157.5,
    'width' => 77.4,
    'depth' => 7.7
);

echo <<<EOT
The height of "iPhone XS Max" is $size[height] mm.

EOT;
echo <<<EOT
The width of "iPhone XS Max" is ${size["width"]} mm.

EOT;
echo <<<EOT
The depth of "iPhone XS Max" is {$size["depth"]} mm.

EOT;

実行結果は、このように3つのケースで正しく表示できている。
SS_20180914_110910_00.png

このように書くとエラーになる:

echo <<<EOT
The height of "iPhone XS Max" is $size["height"] mm.

EOT;

Parse error: syntax error, unexpected '"', expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

heightのケースが、個人的にはとても気持ち悪く感じるというか、配列でキーを文字列で与えるときは引用符で括るっていう文法を、そこだけ無視できていることがしっくりこない。
なので私はwidthかdepthのケースで書くことが多い。このブログみたいにカラー文法表示がうまく働かないケースも考慮すると、depthのケース「{$size["depth"]}」が無難なのかもしれない。
PHP: ヒアドキュメントと連想配列 - m6uのエンジニアっぽい日記からの転載)


参考文献
変数のパース - 文字列

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