views:

55

answers:

5

What is the difference between these code snippets?

1)

$f = 12.044545;  
printf("%f",$f);  
vprintf("%f",$f);  

2)

echo("echo");
print("print");

Thanks,

+1  A: 

echo and print are not actually functions, and return no meaningful value. printf() and vprintf() return the length of the outputted string.

Ignacio Vazquez-Abrams
+2  A: 

Read the manual:

Basically the first two are functions that print formatted output, the other two are language constructs that merely output a string.

Artefacto
+4  A: 
  • printf() lets you specify the format of the variables you want to print
  • vprintf() is the same as printf() but accepts an array as argument instead of a list of scalar variables
  • echo and print do basically the same thing (besides technicalities): printing their argument(s) with no processing other than variable interpolation
kemp
+1  A: 

1) printf and vprintf are almost the same, but vprintf accepts an array of arguments, instead of a variable number of arguments.

2) With echo, you can provide multiple expressions:

echo "Hello ", "Hello again";
print "Hello ", "Hello again"; // <- Error!
Andy E
+1  A: 

printf and vprintf are real functions that format text for output and return a value, whereas echo and print are just operators that output a string.

The printf family of functions are actually from a common family of output functions that go all the way back to the original K&R C and are well worth paying attention too because they occur in virtually all the C-syntax based languages. Get familiar with them in any one context and you'll be able to reach for them elsewhere with minimal trouble. One of the other useful variants on the theme is sprintf, which outputs a printf formatted expression to a string.

Of slightly less use, but also well worth having in the armoury as C heritage is the scanf function family which extracts data from formatted input. Like printf these occur in most C-syntax languages.

Cruachan