- PHP echo and print
- PHP
- PHP
- PHP
- 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!
- echo
- Parameters
- Return Values
- Examples
- Notes
- PHP-оператор echo
- Вывод на экран строк, переменных с помощью echo
- Синтаксис
- Пример: вывод на экран простой строки
- Пример: переменная внутри оператора echo
- echo и HTML-тег параграфа
- Пример: PHP echo и HTML-тег параграфа с различными цветами шрифта
- Пример: echo и с различными цветами и размерами шрифта
- Пример: PHP echo HTML и с различными цветами, размерами шрифта и значениями переменных
- echo и HTML-таблицы
- Пример: echo и HTML- таблица с различными цветами шрифта и переменными PHP
- Пример: PHP echo и HTML-таблица с различными цветами шрифта, рамками и переменными PHP
- echo и ссылки
- Пример: echo и гиперссылка с различными цветами шрифта
- Пример: гиперссылка (PHP echo url)с различными цветами и размерами шрифта
- echo и HTML-элемент заголовка
- This is header2
- Пример: PHP echo, HTML-заголовок и значение переменной
- Salary of Mr. B is : $b$
- Salary of Mr. C is : $c$
- echo и HTML-список
- Пример: PHP echo и HTML-нумерованный список
- Пример: PHP echo и маркированный список
PHP echo and print
In this article, we will see what is echo & print statements in PHP, along with understanding their basic implementation through the examples. The echo is used to display the output of parameters that are passed to it. It displays the outputs of one or more strings separated by commas. The print accepts one argument at a time & cannot be used as a variable function in PHP. The print outputs only the strings.
Note: Both are language constructs in PHP programs that are more or less the same as both are used to output data on the browser screen. The print statement is an alternative to echo.
PHP echo statement: It is a language construct and never behaves like a function, hence no parenthesis is required. But the developer can use parenthesis if they want. The end of the echo statement is identified by the semi-colon (‘;’). It output one or more strings. We can use ‘echo‘ to output strings, numbers, variables, values, and results of expressions. Below is some usage of echo statements in PHP:
Displaying Strings: We can simply use the keyword echo followed by the string to be displayed within quotes. The below example shows how to display strings with PHP.
PHP
Hello,This is a display string example!
Displaying Strings as multiple arguments: We can pass multiple string arguments to the echo statement instead of a single string argument, separating them by comma (‘,’) operator. For example, if we have two strings i.e “Hello” and “World” then we can pass them as (“Hello”, “World”).
PHP
Displaying Variables: Displaying variables with echo statements is also as easy as displaying normal strings. The below example shows different ways to display variables with the help of a PHP echo statement.
PHP
The (.) operator in the above code can be used to concatenate two strings in PHP and the “\n” is used for a new line and is also known as line-break. We will learn about these in further articles.
PHP print statement: The PHP print statement is similar to the echo statement and can be used alternative to echo many times. It is also a language construct, so we may not use parenthesis i.e print or print().
The main difference between the print and echo statement is that echo does not behave like a function whereas print behaves like a function. The print statement can have only one argument at a time and thus can print a single string. Also, the print statement always returns a value of 1. Like an echo, the print statement can also be used to print strings and variables. Below are some examples of using print statements in PHP:
Displaying String of Text: We can display strings with the print statement in the same way we did with echo statements. The only difference is we cannot display multiple strings separated by comma(,) with a single print statement. The below example shows how to display strings with the help of a PHP print statement.
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:
echo
Outputs one or more expressions, with no additional newlines or spaces.
echo is not a function but a language construct. Its arguments are a list of expressions following the echo keyword, separated by commas, and not delimited by parentheses. Unlike some other language constructs, echo does not have any return value, so it cannot be used in the context of an expression.
echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This syntax is available even with the short_open_tag configuration setting disabled.
The major differences to print are that echo accepts multiple arguments and doesn’t have a return value.
Parameters
One or more string expressions to output, separated by commas. Non-string values will be coerced to strings, even when the strict_types directive is enabled.
Return Values
Examples
Example #1 echo examples
echo «echo does not require parentheses.» ;
?php
// Strings can either be passed individually as multiple arguments or
// concatenated together and passed as a single argument
echo ‘This ‘ , ‘string ‘ , ‘was ‘ , ‘made ‘ , ‘with multiple parameters.’ , «\n» ;
echo ‘This ‘ . ‘string ‘ . ‘was ‘ . ‘made ‘ . ‘with concatenation.’ . «\n» ;
// No newline or space is added; the below outputs «helloworld» all on one line
echo «hello» ;
echo «world» ;
// Same as above
echo «hello» , «world» ;
echo «This string spans
multiple lines. The newlines will be
output as well» ;
echo «This string spans\nmultiple lines. The newlines will be\noutput as well.» ;
// The argument can be any expression which produces a string
$foo = «example» ;
echo «foo is $foo » ; // foo is example
$fruits = [ «lemon» , «orange» , «banana» ];
echo implode ( » and » , $fruits ); // lemon and orange and banana
// Non-string expressions are coerced to string, even if declare(strict_types=1) is used
echo 6 * 7 ; // 42
// Because echo does not behave as an expression, the following code is invalid.
( $some_var ) ? echo ‘true’ : echo ‘false’ ;
// However, the following examples will work:
( $some_var ) ? print ‘true’ : print ‘false’ ; // print is also a construct, but
// it is a valid expression, returning 1,
// so it may be used in this context.
echo $some_var ? ‘true’ : ‘false’ ; // evaluating the expression first and passing it to echo
?>
Notes
Note: Because this is a language construct and not a function, it cannot be called using variable functions, or named arguments.
Note: Using with parentheses
Surrounding a single argument to echo 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 echo syntax itself.
echo( «hello» );
// also outputs «hello», because («hello») is a valid expression
echo( 1 + 2 ) * 3 ;
// outputs «9»; the parentheses cause 1+2 to be evaluated first, then 3*3
// the echo statement sees the whole expression as one argument
echo «hello» , » world» ;
// outputs «hello world»
echo( «hello» ), ( » world» );
// outputs «hello world»; the parentheses are part of each expression
echo( «hello» , » world» );
// Throws a Parse Error because («hello», » world») is not a valid expression
?>
Passing multiple arguments to echo can avoid complications arising from the precedence of the concatenation operator in PHP. For instance, the concatenation operator has higher precedence than the ternary operator, and prior to PHP 8.0.0 had the same precedence as addition and subtraction:
// Below, the expression ‘Hello ‘ . isset($name) is evaluated first,
// and is always true, so the argument to echo is always $name
echo ‘Hello ‘ . isset( $name ) ? $name : ‘John Doe’ . ‘!’ ;
?php
// The intended behaviour requires additional parentheses
echo ‘Hello ‘ . (isset( $name ) ? $name : ‘John Doe’ ) . ‘!’ ;
// In PHP prior to 8.0.0, the below outputs «2», rather than «Sum: 3»
echo ‘Sum: ‘ . 1 + 2 ;
// Again, adding parentheses ensures the intended order of evaluation
echo ‘Sum: ‘ . ( 1 + 2 );
If multiple arguments are passed in, then parentheses will not be required to enforce precedence, because each expression is separate:
echo «Hello » , isset( $name ) ? $name : «John Doe» , «!» ;
?php
PHP-оператор echo
Основными конструкциями PHP для вывода являются echo и print . Но PHP echo() не является функцией, это конструкция языка, поэтому вы можете использовать ее без скобок.
Вывод на экран строк, переменных с помощью echo
Синтаксис
Пример: вывод на экран простой строки
'; echo 'Two line simple string example
'; echo 'Tomorrow I 'll learn PHP global variables.
'; echo 'This is a bad command : del c:\*.*
'; ?>
Все перечисленные выше вызовы выводят на экран соответствующую строку. В конце каждого echo PHP синтаксиса мы использовали для переноса строки дополнительную HTML-команду
, так как n не может создавать разрывы строк в браузере.
Пример: переменная внутри оператора echo
"; // Отображение простой переменной echo $abc; echo "
"; // создаем новую строку echo $xyz; echo "
"; // создаем новую строку // Отображаем массивы $fruits=array('fruit1'=>'Apple','fruit2'=>'Banana'); echo "Fruits are : and " ; ?>
We are learning PHP at w3resource.com We are learning PHP w3resource.com Fruits are: Apple and Banana
echo и HTML-тег параграфа
С помощью PHP echo выводятся array, строки, переменные. Кроме этого можно встраивать в echo команды HTML . В приведенном ниже примере мы присоединяем к echo тег
.
'; // отображаем строки внутри параграфа разным цветом. echo "One line simple string in blue color
"; echo "One line simple string in red color
"; echo "One line simple string in green color
"; ?>
Посмотреть пример в браузере
Пример: PHP echo и HTML-тег параграфа с различными цветами шрифта
'; // отображаем строки внутри параграфа разным цветом. echo "One line simple string in blue color, arial font and font size 2pt
"; echo "One line simple string in red color, verdana font and font size 5pt
"; echo "One line simple string in green color, courier font and font size 6pt
"; ?>
Посмотреть пример в браузере
Пример: echo и
с различными цветами и размерами шрифта
This is left alignment 6pt "; echo "This is center alignment 6pt
"; echo "This is right alignment 6pt
"; ?>
Посмотреть пример в браузере
Пример: PHP echo HTML и
с различными цветами, размерами шрифта и значениями переменных
Salary of Mr. A is : $a$"; echo "Salary of Mr. B is : $b$
"; echo "Salary of Mr. C is : $c$
"; ?>
Посмотреть пример в браузере
echo и HTML-таблицы
В приведенном ниже примере мы в различной форме присоединяем к PHP echo HTML-таблицу .
Salary of Mr. A is $a$ Salary of Mr. B is $b$ "; ?> Salary of Mr. C is $c$
Посмотреть пример в браузере
Пример: echo и HTML- таблица с различными цветами шрифта и переменными PHP
Salary of Mr. A is $a$ Salary of Mr. B is $b$ "; ?> Salary of Mr. C is $c$
Посмотреть пример в браузере
Пример: PHP echo и HTML-таблица с различными цветами шрифта, рамками и переменными PHP
Monthly Salary Statement "; echo "
Salary of Mr. A is | $a$ |
Salary of Mr. B is | $b$ |
Salary of Mr. C is | $c$ |
Посмотреть пример в браузере
echo и ссылки
В приведенном ниже примере мы в различной форме присоединили к PHP echo HTML-элемент ссылки.
Посмотреть пример в браузере
Пример: echo и гиперссылка с различными цветами шрифта
Посмотреть пример в браузере
Пример: гиперссылка (PHP echo url)с различными цветами и размерами шрифта
Посмотреть пример в браузере
echo и HTML-элемент заголовка
В приведенном ниже примере мы присоединяем к echo HTML- заголовок .
This is header1 "; echo "This is header2
"; echo " This is header3 "; echo " This is header4 "; echo " This is header5 "; echo " This is header6 "; ?>
Посмотреть пример в браузере
Пример: PHP echo, HTML-заголовок и значение переменной
Salary of Mr. A is : $a$ "; echo "Salary of Mr. B is : $b$
"; echo "Salary of Mr. C is : $c$
"; ?>
Посмотреть пример в браузере
echo и HTML-список
С помощью echo можно отобразить строку, переменную и встраивать команды HTML . В приведенных ниже примерах мы присоединяем к echo нумерованные и маркированные списки.
Пример: PHP echo и HTML-нумерованный список
Посмотреть пример в браузере
Пример: PHP echo и маркированный список
Посмотреть пример в браузере