- php echo command with examples
- Php echo command:
- Html tags in PHP echo:
- Php echo Single quotes and double quotes:
- Difference between PHP echo and PHP print commands:
- echo
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- 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!
- PHP echo and print
- PHP
- PHP
- PHP
php echo command with examples
PHP echo command with examples-hello everyone in this article what I’ll be covering is the PHP echo command, and I know I have been using the PHP echo command several times in the previous articles. but the echo command is probably gonna be one of the most used PHP commands that you use while you’re coding PHP code so it really does deserve its own article because you can do so many great things with the PHP echo command so let’s just go ahead and jump into coding…
Php echo command:
With the PHP echo command you can output content or text to the browser you know by sending that data to the server and the server sends that back to the browser is plain HTML so let’s just review a little bit about how you can output a string or integer to the browser. For example I use a variable at this time let’s say we have a variable called $aString and we’re gonna assign the string hello programming digest to that variable
and let’s create another variable and we’re gonna call it int and we’re gonna assign the value 300 to it
In the above instruction, we can tell PHP that aString again is a string variable because of the double quotes and we can tell that int is an integer variable because it doesn’t have quotes.
so what the PHP echo command, what we can do here is an echo out what’s inside aString variable simply by typing echo aString and followed by a semicolon
go ahead and save the above code into your folder which is in your htdocs folder I’m gonna save it with the name echo.php. now type localhost slash foldername slash filename into your browser and press enter
so as we see in the below figure it says programming digest
Html tags in PHP echo:
we can also use HTML tags within the PHP echo command so let’s say for example I’m gonna use the same variables here let’s say I’m gonna make programming digest text bold, and again I expect you to know some of the basic concepts of some of the basic HTML tags that you can use
as you can see I used the bold tag so the text should be bold. so I’m just gonna go ahead and save the file and refresh the browser and as you can see programming digest is bold
let’s make programming digest text underlined, I am using the same variables as you can see
so again these are just some basic HTML tags, so save the file and refresh the browser and then you see programming digest.. is underlined so it’s really neat that you can use HTML within PHP but it’s very important that you use the correct HTML syntax or of course, you’re gonna have issues or so now that I have exposed you to the concept of using HTML with a PHP echo command.
Php echo Single quotes and double quotes:
you really have to be careful when echoing quotes or double quotes the reason being is any other string or HTML code that uses quotes can also cause problems when using the PHP echo command see the echo uses quotes to define the beginning of the string and the end of the string. for example, we want to display an image in the web browser so I’m gonna say
echo «» ;
then end it with another single quote then followed by a greater than sign then followed by a double quote and then a semicolon.
echo «» ;
Save the above code and refresh the browser As you can see our image is displayed in a web browser. So in this way we use single and double quotes in PHP echo.
Difference between PHP echo and PHP print commands:
We have already seen various ways of using the PHP echo command to output text from the server to the browser. In some cases, a string literal is displayed, in others, strings were concatenated or the values of variables were calculated first. The output was also shown spanning multiple lines. But there is an alternative to the PHP echo command that you can also use: the print command. These two commands are very similar to each other, but print construction, like a function that takes a single parameter and has a return value (which is always 1), and echo is a pure PHP construct.
In general, PHP echo works faster than print on plain text output because it does not set the return value. On the other hand, since it is not a function, unlike print, it cannot be used as part of a more complex expression. The following example uses the print function to display information about whether the value of a variable is TRUE or FALSE, but it is not possible to do the same with the PHP echo command since it will display a message Parse error:
echo
На самом деле echo — это не функция, а конструкция языка, поэтому заключать аргументы в скобки необязательно. echo (в отличии от других языковых конструкций) не ведет себя как функция, поэтому не всегда может быть использована в контексте функции. Вдобавок, если вы хотите передать более одного аргумента в echo, эти аргументы нельзя заключать в скобки.
echo имеет также краткую форму, представляющую собой знак равенства, следующий непосредственно за открывающим тэгом. До версии PHP 5.4.0, этот сокращенный синтаксис допускался только когда включена директива конфигурации short_open_tag.
Список параметров
Возвращаемые значения
Эта функция не возвращает значения после выполнения.
Примеры
Пример #1 Примеры использования echo
echo «Это займет
несколько строк. Переводы строки тоже
выводятся» ;
echo «Это займет\nнесколько строк. Переводы строки тоже\nвыводятся» ;
echo «Экранирование символов делается \»Так\».» ;
// с echo можно использовать переменные .
$foo = «foobar» ;
$bar = «barbaz» ;
echo «foo — это $foo » ; // foo — это foobar
// . и массивы
$baz = array( «value» => «foo» );
// При использовании одиночных кавычек выводится имя переменной, а не значение
echo ‘foo — это $foo’ ; // foo — это $foo
// Если вы не используете другие символы, можно вывести просто значения переменных
echo $foo ; // foobar
echo $foo , $bar ; // foobarbarbaz
// Некоторые предпочитают передачу нескольких аргументов вместо конкатенации
echo ‘Эта ‘ , ‘строка ‘ , ‘была ‘ , ‘создана ‘ , ‘несколькими параметрами.’ , chr ( 10 );
echo ‘Эта ‘ . ‘строка ‘ . ‘была ‘ . ‘создана ‘ . ‘с помощью конкатенации.’ . «\n» ;
echo Здесь используется синтаксис «here document» для вывода
нескольких строк с подстановкой переменных $variable .
Заметьте, что закрывающий идентификатор должен
располагаться в отдельной строке. никаких пробелов!
END;
// Следующая строка неверна, так как echo не является функцией
( $some_var ) ? echo ‘true’ : echo ‘false’ ;
// Но это можно записать по другому
( $some_var ) ? print ‘true’ : print ‘false’ ; // print также является конструкцией языка,
// но ведет себя как функция, поэтому она
// может быть использована в этом контексте.
echo $some_var ? ‘true’ : ‘false’ ; // echo вынесен за пределы выражения
?>
Примечания
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.
Смотрите также
- print — Выводит строку
- printf() — Выводит отформатированную строку
- flush() — Сброс системного буфера вывода
- Heredoc синтаксис
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:
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.