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

Hàm print() trong PHP

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

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

The print() function outputs a string.

The following table summarizes the technical details of this function.

Return Value: Returns 1, always.
Version: PHP 4+

Syntax

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

print(string);

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

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

Tip: The print is not actually a function, it is a language construct (like if statement), so you can use it without parentheses. Alternatively, you can also use echo to output a string.


Parameters

The print() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to be sent to the output.

More Examples

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

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

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

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

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

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

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

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

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

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

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

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

Bài viết mới

Advertisements