print

(PHP 4, PHP 5, PHP 7, PHP 8)

print文字列を出力する

説明

print(string $expression): int

expression を出力します。

printは実際には関数ではなく、 言語構造です。 引数は、print の後に文字列として評価される式を指定し、括弧で括る必要はありません。

echo との主な違いは、 print が単一の引数のみ受け付け、常に 1 を返すことです。

パラメータ

expression

出力する文字列として評価される式。 文字列として評価できない値は、 強制的に文字列に変換されます。 これは、 strict_types ディレクティブ が有効になっていても同じです。

戻り値

常に 1 を返します。

例1 print の例

<?php
print "print に括弧は不要です";

// 改行やスペースは付加されません; 以下は、"helloworld" を一行で出力します
print "hello";
print
"world";

print
"This string spans
multiple lines. The newlines will be
output as well"
;

print
"This string spans\nmultiple lines. The newlines will be\noutput as well.";

// 引数は文字列を生成するあらゆる式を指定することができます。
$foo = "example";
print
"foo is $foo"; // foo is example

$fruits = ["lemon", "orange", "banana"];
print
implode(" and ", $fruits); // lemon and orange and banana

// 文字列でない値は、文字列に強制されます。たとえ declare(strict_types=1) が使われていても同じです。
print 6 * 7; // 42

// print は戻り値があるため、式の中で使うことができます。
// 以下は "hello world" を出力します。
if ( print "hello" ) {
echo
" world";
}

// 以下は "true" を出力します。
( 1 === 1 ) ? print 'true' : print 'false';
?>

注意

注意: 括弧を使う

printの引数を括弧で囲んで渡しても文法エラーにはなりませんが、 通常の関数コールのような文法に見えてしまいます。 しかし、これは誤解を招く恐れがあります。 なぜなら、括弧は実際には出力を構成する式の一部であり、 print の文法の一部ではないからです。

<?php
print "hello";
// "hello" を出力します。

print("hello");
// 同じく"hello" を出力します。なぜなら ("hello") は正しい式だからです。

print(1 + 2) * 3;
// "9" を出力します; 括弧によって 1+2 が先に評価され、3*3がその次に評価されます。
// print 文は、式の評価結果全体をひとつの引数とみなします。

if ( print("hello") && false ) {
print
" - inside if";
}
else {
print
" - inside else";
}
// " - inside if" を出力します。
// ("hello") && false という式が最初に評価され、
// 評価された false が空文字列 "" に強制的に変換され、print に渡され、1を返します。
// よって、if ブロックの内部のコードが実行されます。
?>

print を大きな式で使う場合、 意図した結果を得るためには、キーワードと引数を括弧で囲む必要があるかもしれません:

<?php
if ( (print "hello") && false ) {
print
" - inside if";
}
else {
print
" - inside else";
}
// "hello - inside else" を出力します。
// 直前の例と異なり、(print "hello") が最初に評価され、
// "hello" を出力した後、print が1を返します。
// 1 && false は false なので、else ブロックの中身が実行されます。

print "hello " && print "world";
// "world1"; を出力します。print "world" が先に評価され、
// "hello " && 1 が次に評価され、左辺の print に渡されます。

(print "hello ") && (print "world");
// "hello world" を出力します; 括弧が print を && より前に評価させているからです。
?>

注意: これは、関数ではなく 言語構造のため、可変関数名前付き引数 を用いてコールすることはできません。

参考