文字列や変数の値を出力するには、「echo」や「print」を使います。
どちらを使っても構いません。
[short_color title=”printとは” class=”info”]「print」「echo」 は、1つ以上の文字列を出力する言語構造です。 [/short_color]
文字列
echo と同じく、出力させたい文字列をシングルクォーテーション、またはダブルクォーテーションで囲み、最後にセミコロンをつけます。
<?php
print '文字列を表示する';
?>
<?php
print "文字列を表示する";
?>
[short_color title=”結果” class=”nomal”]文字列を表示する [/short_color]
いずれも結果は同じです。
数式
シングルクォーテーション、またはダブルクォーテーションで囲み、文字列として出力します。
<?php
print '2 * 3';
print '<br>';
print '6 / 3';
?>
[short_color title=”結果” class=”nomal”]2 * 3
6 / 3 [/short_color]
計算結果
シングルクォーテーション、またはダブルクォーテーションは不要です。
<?php
print 2 * 3;
print '<br>';
print 6 / 3;
?>
6
2
[short_color title=”結果” class=”nomal”]6
2 [/short_color]
変数
変数の場合もシングルクォーテーション、またはダブルクォーテーションは不要です。
<?php
$a = "こんにちは ^^";
print $a;
?>
[short_color title=”結果” class=”nomal”]こんにちは ^^ [/short_color]
変数をシングルクォーテーションで囲むとどうなるか
<?php
$a = "こんにちは ^^";
print '$a';
?>
[short_color title=”結果” class=”nomal”]$a [/short_color]
「$a」という文字列になり、変数の値は出力されません。
変数をダブルクォーテーションで囲むとどうなるか
<?php
$a = "こんにちは ^^";
print "$a";
?>
[short_color title=”結果” class=”nomal”]こんにちは ^^ [/short_color]
ダブルクォーテーションで変数を囲むと、変数の値が出力されます。
文字列と数字を繋げる
<?php
$a = 3;
print 'ねこが' . $a . '匹います。';
?>
[short_color title=”結果” class=”nomal”]ねこが3匹います。 [/short_color]