Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php : echo"", print(), printf()

Tags:

syntax

php

Is there a better way to output data to html page with PHP?

If I like to make a div with some var in php, I will write something like that

print ('<div>'.$var.'</div>'); 

or

echo "'<div>'.$var.'</div>'"; 

What is the proper way to do that?

Or a better way, fill a $tempvar and print it once? like that:

$tempvar = '<div>'.$var.'</div>' print ($tempvar); 

In fact, in real life, the var will be fill with much more!

like image 801
menardmam Avatar asked Oct 01 '09 15:10

menardmam


People also ask

What is difference between echo print and printf in PHP?

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 .

Can I use printf in PHP?

Definition and Usage. The printf() function outputs a formatted string. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step".

What is the use of Print_r in PHP?

It is a built-in function in print_r in PHP that is used to print or display the contents of a variable. It essentially prints human-readable data about a variable. The value of the variable will be printed if it is a string, integer, or float.


1 Answers

There are 2 differences between echo and print in PHP:

  • print returns a value. It always returns 1.

  • echo can take a comma delimited list of arguments to output.

Always returning 1 doesn't seem particularly useful. And a comma delimited list of arguments can be simulated with multiple calls or string concatenation. So the choice between echo and print pretty much comes down to style. Most PHP code that I've seen uses echo.

printf() is a direct analog of c's printf(). If you're comfortable in the c idiom, you might use printf(). A lot of people in the younger generation though, find printf()'s special character syntax to be less readable than the equivalent echo code.

There are probably differences in performance between echo, print and printf, but I wouldn't get too hung up on them since in a database driven web application (PHP's typical domain), printing strings to the client is almost certainly not your bottleneck. The bottom line is that any of the 3 will get the job done and one is not better than another. It's just a matter of style.

like image 162
Asaph Avatar answered Sep 20 '22 21:09

Asaph