分类: PHP

PHP – Sending Data to Browser






Different between echo(),print(),printf() and sprintf()

Different between single quoted [ ‘ ]double quoted [ ” ]

print()

the most straightforward method

int print  (string $arg)

print() accepts one argument, which is string to be output to browser, and return an integer — print() always returns 1

echo()

the most common method of generation output.

void echo (stirng $arg1 [,string $...])

echo() statement accepts one or more arguments, separated by commas, and outputs all of the arguments to the browser in succession. echo() does not return a value

$foo = "Hello";
$bar = "World!";
echo $foo,$bar;

//output : Hello World!

printf()

printf() gives you more fine-grained control over your output,allowing you to define the format of data that will be send to the browser.You can think of this statement as meaning “print formated” this is especially useful when your’re dealing with numbers which i’ll cover in a moment.

printf("PHP is %s!", "awesome");
//output: PHP is awesome!

$amt1 = 2.55;
$amt2 =3.55;
$total = $amt1 + $amt2;
printf('The total cost is $.2f',$total)
//output: The total cost is $6.10
echo 'The total cost is $',$total;
//output: The total cost is $6.1

sprintf()

sprintf() works in the same way as the printf(). You provide a format with type specifiers and set of arguments to be inserted into your formatting string. The only difference is that while printf() outputs directly to the browser, sprintf() returns a string.

$gpa1 = sprintf("%1.f",4);
$gpa2 = sprintf("%1.f",3.7);
echo 'kelly had a ',$gpa1,'GPA, and Tom had a ',$gpa2;
//output : Kelly had a 4.0 GPA, and Tom had a 3.7

single quoted [ ‘ ], double quoted [ ” ]

Single quoted strings are the easiest way to specify string. This method in used when we want to the string to be exactly as it is written. When string is specified in single quotes PHP will not evaluate it or interpret escape characters except single quote with backslash (‘) and backslash(\) which has to be escaped.

echo This is \'test\' string';
//Output: This is 'test' string

$count= 1;
echo "The count is $count";
//Output: The count is 1

$count= 1;
echo 'The count is $count';
//Output: The count is $count




发表评论