Home >Backend Development >PHP Problem >What is the difference between php printf and echo?

What is the difference between php printf and echo?

青灯夜游
青灯夜游Original
2020-09-01 11:22:292488browse

The difference between printf and echo in php: 1. echo is a command that can output multiple variables, such as "echo $a,$b;"; 2. printf is a function that can output formatted String, for example "printf("Variable a is %u, b is a %s",$a,$b);".

What is the difference between php printf and echo?

Recommended: "PHP Video Tutorial"

echo can output multiple variables

<?php
$a=1;
$b=2;
echo $a,$b;
?>

echo is a command and cannot return a value. Echo can be followed by many parameters, separated by semicolons, such as:

echo $myvar1;
echo 1,2,$myvar,"bold";

print can only output one variable at a time

print is a function and can return A value can only have one parameter.

<?php
	$a=1;
	$b=2;
	print $a;
	print $b;
?>

printf is a mixture of static text and variables

The printf function formats the text and outputs it. For example:

<?php
$a=1;
$b="变量";
printf("变量a为%u,b是一个%s",$a,$b)
?>

The result is

What is the difference between php printf and echo?

Possible format values ​​in printf:

%% - Returns a percent sign %

%b - Binary number

%c - Character corresponding to the ASCII value

%d - Decimal number containing a plus or minus sign (negative number , 0, positive number)

%e - Use lowercase scientific notation (for example, 1.2e 2)

%E - Use uppercase scientific notation (for example, 1.2E 2)

%u - Decimal number without sign (greater than or equal to 0)

%f - Floating point number (local setting)

%F - Floating point number (non-local setting) )

%g - Shorter %e and %f

%G - Shorter %E and %f

%o - Octal number

%s - string

%x - hexadecimal number (lower case letters)

%X - hexadecimal number (upper case letters)

Additional formats value. Must be placed between % and a letter (such as %.2f):

(Add or - in front of the number to define the sign of the number. By default, only negative numbers are marked, and positive numbers are not marked. )

' (Specifies what to use as padding, defaults to spaces. It must be used with a width specifier.)

-(Left adjustment variable value)

[0 -9] (Specifies the minimum width of the variable value)

.[0-9] (Specifies the number of decimal places or the maximum string length)

Note: If you use more than one of the above format values, they must be used in the order above and cannot be disrupted

The above is the detailed content of What is the difference between php printf and echo?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn