文字列や変数の値を出力するには、「echo」や「print」を使います。
どちらを使っても構いません。
[short_color title=”echoとは” class=”info”]「echo」「print」 は、1つ以上の文字列を出力する言語構造です。 [/short_color]
文字列
出力させたい文字列をシングルクォーテーション、またはダブルクォーテーションで囲み、最後にセミコロンをつけます。
<?php
echo '文字列を表示する';
?>
または
<?php
echo "文字列を表示する";
?>
[short_color title=”結果” class=”nomal”]文字列を表示する [/short_color]
いずれも結果は同じです。
文字列を繋げる場合
カンマで区切って繋げることができます。
<?php
echo 'あいうえお' , 'かきくけこ' , 'さしすせそ';
?>
[short_color title=”結果” class=”nomal”]あいうえおかきくけこさしすせそ [/short_color]
数式
シングルクォーテーション、またはダブルクォーテーションで囲み、文字列として出力します。
<?php
echo '2 + 3';
echo '<br>';
echo "5 - 3";
?>
[short_color title=”結果” class=”nomal”]2 + 3
5 – 3 [/short_color]
※<br>はHTMLタグの改行です。
計算結果
シングルクォーテーション、またはダブルクォーテーションは不要です。
<?php
echo 2 + 3;
echo '<br>';
echo 5 - 3;
?>
[short_color title=”結果” class=”nomal”]5
2 [/short_color]
変数
変数の場合もシングルクォーテーション、またはダブルクォーテーションは不要です。
<?php
$a = "おはようございます";
echo $a;
?>
[short_color title=”結果” class=”nomal”]おはようございます [/short_color]
変数をシングルクォーテーションで囲むとどうなるか
<?php
$a = "初めまして";
echo '$a';
?>
[short_color title=”結果” class=”nomal”]$a [/short_color]
「$a」という文字列になり、変数の値は出力されません。
変数をダブルクォーテーションで囲むとどうなるか
<?php
$a = "初めまして";
echo "$a";
?>
[short_color title=”結果” class=”nomal”]初めまして [/short_color]
ダブルクォーテーションで変数を囲むと、変数の値が出力されます。
文字列と数字を繋げる
文字列と数字を繋げる場合は、ドット(.)を使います。
<?php
$a = 3;
echo 'ねこが' . $a . '匹います。';
?>
[short_color title=”結果” class=”nomal”]ねこが3匹います。 [/short_color]