0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP echoとprintについて

Last updated at Posted at 2020-06-19

PHP echoとprintの違いについて

PHPには echo と print というよく似た出力機能があります。
今回はこの二つの機能の違いについて調べてみました。

関数ではない

echoとprintはどちらも厳密には関数ではなく、PHPの言語構造だと説明されています。
そのため()をつけなくても正常に動作します。
https://www.php.net/manual/ja/function.echo.php
https://www.php.net/manual/ja/function.print.php

test1.php
<?php
    print("Hello world\n");
    print "Hello world\n";

    echo("Hello world\n");
    echo "Hello world\n";
?>

出力結果

Hello world
Hello world
Hello world
Hello world

動作の違いとしては、echo()はカンマ「,」区切りで複数の引数を指定できるのに対し、print()はできません。
※ただし、echo文でも()をつけるとエラーが出ます。

test2.php
<?php
    print 'Hello', 'world'; // この構文はエラーが出ます
    echo 'Hello', 'world'; // こっちは正しい構文です
?>

printは式(expression )、 echoは式ではない(statement)

例えば、echoをif式で評価することはできませんが、printは評価することができます。
printは常に1を返すため、以下のような書き方ができます。

test3.php
<?php	
	//正常に評価する
	if (print 1) {
   		 print 'success';
	}
?>

処理結果

1success

echo で上記のような書き方をするとエラーとなります。

どちらを使えばよいか

結論から言えばどちらでもよさそうです。
返り値を持たない分、echoの方が処理速度が速いらしいですが、体感できるほどの差はないかと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?