Hướng dẫn
Quảng cáo

Hàm echo() trong PHP

Hướng dẫn cách sử dụng hàm echo() trong lập trình PHP

Tác dụng của hàm echo()

The echo() function outputs one or more strings.

The following table summarizes the technical details of this function.

Return Value: No value is returned.
Version: PHP 4+

Syntax

The basic syntax of the echo() function is given with:

echo(strings);

The following example shows the echo() function in action.

Ví dụ

<?php
echo "Hello World!";
?>
 

Tip: The echo is not actually a function, it is a language construct (like if statement), so you can use it without parentheses. Also, echo is considered marginally faster than the print (an alternative to echo) since it doesn't return any value.


Parameters

The echo() function accepts the following parameters.

Parameter Description
strings Required. One or more strings to be sent to the output.

More Examples

Here're some more examples showing how echo() function actually works:

The following example shows how to print multiple strings at once using concatenation operator.

Ví dụ

<?php
// Defining variable
$str1 = "Hi There";
$str2 = "Have a nice day";

// Printing variables values
echo $str1 . "! " . $str2 . " :)";

// Above statement can also be written as
echo "$str1! $str2 :)";
?>

You can also print variable value as well as HTML tags using the echo statement, like this:

Ví dụ

<?php
// Defining variable
$age = 18;

// Printing variable value
echo "<h1>Your age is $age.</h1>";
?>

If you use single quote ('), variable will be displayed literally instead of value, as shown here:

Ví dụ

<?php
// Defining variable
$color = "blue";

echo "Sky is $color"; // Prints: Sky is blue
echo 'Sky is $color'; // Prints: Sky is $color
?>

The echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign, to quickly print variable value inside HTML, as shown below:

Ví dụ

<?php
// Defining variable
$name = "John";
?>

<!--Printing variable value inside HTML-->
<p>Hi, <?= $name ?>. Good to see you.</p>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements