- Операторы PHP echo и print
- Оператор echo
- Пример
- Пример
- Оператор print
- Пример
- Пример
- PHP echo and print Statements
- PHP echo and print Statements
- The PHP echo Statement
- Example
- PHP is Fun!
- Example
- » . $txt1 . «
- The PHP print Statement
- Example
- PHP is Fun!
- Parameters
- Return Values
- Examples
- Notes
- See Also
- PHP print() Function
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- Example
- Example
- Example
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
Операторы PHP echo и print
В PHP есть два основных способа вывода данных: echo и print .
Операторы echo и print делают одно и то же — выводят данные на экран, но всё же имеют и некоторые отличия. Отличия невелики: echo не имеет возвращаемого значения и может принимать несколько параметров (хотя это используется редко), а print при использовании возвращает значение 1, поэтому может быть использован в выражениях и принимает только один аргумент.
Оператор echo
Оператор echo — выводит одну или более строк.
На самом деле, echo — это не функция (это языковая конструкция), поэтому заключать параметры в скобки () необязательно.
echo можно писать двумя способами с круглыми скобками и без них: echo или echo() . Если вы используете синтаксис с круглыми скобками, то передать можно только один аргумент. При использовании синтаксиса без скобок, можно передавать несколько аргументов, разделяя их запятыми.
В следующем примере показано, как вывести текст с помощью команды echo (обратите внимание, что текст может содержать разметку HTML):
Пример
echo "PHP это легко!
";
echo "Сейчас я изучаю PHP!
";
echo "Эта ", "строка ", "была ", "сделана ", "из нескольких аргументов.";
?>
Теперь рассмотрим вывод текста вместе с переменными:
Пример
$txt1 = "PHP это легко!";
$txt2 = "wmschool.ru";
$x = 3;
$y = 8;
echo "" . $txt1 . "
";
echo "Сейчас я изучаю PHP на " . $txt2 . "
";
echo $x + $y;
?>
echo имеет также краткую форму, представляющую собой знак равенства (=) , следующий непосредственно за открывающим тэгом short_open_tag настроек PHP включена:
Оператор print
print не является «настоящей» функцией (это конструкция языка) поэтому, как и echo можно писать в двух вариантах (со скобками и без них): print или print() . Но в отличие от echo , какой бы вариант написания вы ни выбрали, print может принять только один аргумент.
В следующем примере показано, как вывести текст с помощью print команды (обратите внимание, что текст может содержать разметку HTML):
Пример
print "PHP это легко!
";
print "Сейчас я изучаю PHP!
";
print "И мне это нравится.";
?>
Вывод текста вместе с переменными:
Пример
$txt1 = "PHP это легко!";
$txt2 = "wmschool.ru";
$x = 3;
$y = 8;
print "" . $txt1 . "
";
print "Сейчас я изучаю PHP на " . $txt2 . "
";
print $x + $y;
?>
PHP echo and print Statements
With PHP, there are two basic ways to get output: echo and print .
In this tutorial we use echo or print in almost every example. So, this chapter contains a little more info about those two output statements.
PHP echo and print Statements
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print .
The PHP echo Statement
The echo statement can be used with or without parentheses: echo or echo() .
Display Text
The following example shows how to output text with the echo command (notice that the text can contain HTML markup):
Example
echo «
PHP is Fun!
«;
echo «Hello world!
«;
echo «I’m about to learn PHP!
«;
echo «This «, «string «, «was «, «made «, «with multiple parameters.»;
?>?php
Display Variables
The following example shows how to output text and variables with the echo statement:
Example
echo «
» . $txt1 . «
«;
echo «Study PHP at » . $txt2 . «
«;
echo $x + $y;
?>
The PHP print Statement
The print statement can be used with or without parentheses: print or print() .
Display Text
The following example shows how to output text with the print command (notice that the text can contain HTML markup):
Example
print «
PHP is Fun!
«;
print «Hello world!
«;
print «I’m about to learn PHP!»;
?>?php
Display Variables
The following example shows how to output text and variables with the print statement:
print is not a function but a language construct. Its argument is the expression following the print keyword, and is not delimited by parentheses.
The major differences to echo are that print only accepts a single argument and always returns 1 .
Parameters
The expression to be output. Non-string values will be coerced to strings, even when the strict_types directive is enabled.
Return Values
Examples
Example #1 print examples
print «print does not require parentheses.» ;
?php
// No newline or space is added; the below outputs «helloworld» all on one line
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.» ;
// The argument can be any expression which produces a string
$foo = «example» ;
print «foo is $foo » ; // foo is example
$fruits = [ «lemon» , «orange» , «banana» ];
print implode ( » and » , $fruits ); // lemon and orange and banana
// Non-string expressions are coerced to string, even if declare(strict_types=1) is used
print 6 * 7 ; // 42
// Because print has a return value, it can be used in expressions
// The following outputs «hello world»
if ( print «hello» ) echo » world» ;
>
// The following outputs «true»
( 1 === 1 ) ? print ‘true’ : print ‘false’ ;
?>
Notes
Note: Using with parentheses
Surrounding the argument to print with parentheses will not raise a syntax error, and produces syntax which looks like a normal function call. However, this can be misleading, because the parentheses are actually part of the expression being output, not part of the print syntax itself.
print( «hello» );
// also outputs «hello», because («hello») is a valid expression
print( 1 + 2 ) * 3 ;
// outputs «9»; the parentheses cause 1+2 to be evaluated first, then 3*3
// the print statement sees the whole expression as one argument
if ( print( «hello» ) && false ) print » — inside if» ;
>
else print » — inside else» ;
>
// outputs » — inside if»
// the expression («hello») && false is first evaluated, giving false
// this is coerced to the empty string «» and printed
// the print construct then returns 1, so code in the if block is run
?>
When using print in a larger expression, placing both the keyword and its argument in parentheses may be necessary to give the intended result:
if ( (print «hello» ) && false ) print » — inside if» ;
>
else print » — inside else» ;
>
// outputs «hello — inside else»
// unlike the previous example, the expression (print «hello») is evaluated first
// after outputting «hello», print returns 1
// since 1 && false is false, code in the else block is run
?php
print «hello » && print «world» ;
// outputs «world1»; print «world» is evaluated first,
// then the expression «hello » && 1 is passed to the left-hand print
(print «hello » ) && (print «world» );
// outputs «hello world»; the parentheses force the print expressions
// to be evaluated before the &&
?>
Note: Because this is a language construct and not a function, it cannot be called using variable functions, or named arguments.
See Also
- echo — Output one or more strings
- printf() — Output a formatted string
- flush() — Flush system output buffer
- Ways to specify literal strings
PHP print() Function
Note: The print() function is not actually a function, so you are not required to use parentheses with it.
Tip: The print() function is slightly slower than echo().
Syntax
Parameter Values
Technical Details
More Examples
Example
Write the value of the string variable ($str) to the output:
Example
Write the value of the string variable ($str) to the output, including HTML tags:
Example
Join two string variables together:
Example
Write the value of an array to the output:
Example
Write some text to the output:
Example
Difference of single and double quotes. Single quotes will print the variable name, not the value:
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.