What is the difference between echo, print, var_export in PHP?

4

A difference between var_dump and print_r you already have in this answer . But it does not give any details regarding the echo , print and var_export .

What is the difference between echo , print , var_export in PHP?

    
asked by anonymous 11.10.2017 / 07:29

2 answers

3

As for the comparison between echo and print :

  • Both are language constructors and not function;
  • print receives only one value, while echo receives as many as needed;
  • print always returns an int 1, while echo has no return;
  • print can be used in expressions, echo not (only real difference between them);
  • Using both as statatement produces an equivalent result, with the same side effects, being echo slightly faster, since print uses echo internally;

This difference has already been discussed here:

What is the difference between print and echo in PHP

echo or print, what really is the best option?

var_export

var_export fits more in the same category of var_dump and print_r , usually used for debug . Its usage closely resembles var_dump , however, instead of displaying detailed information about the expression, such as types, sizes, etc., var_export displays a valid representation of the expression. A valid representation is a text that has a syntax allowed by PHP. It is especially useful when you need to store the value of an expression in a log , for example, that you can copy / paste to an editor and perform test operations on it.

Compare the exits of var_dump with var_export :

// var_dump([1, 2, 3, 4, 5]);
array(5) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
  [3]=> int(4)
  [4]=> int(5)
}

// var_export([1, 2, 3, 4, 5])
array (
  0 => 1,
  1 => 2,
  2 => 3,
  3 => 4,
  4 => 5,
) 

If the second parameter of var_export is evaluated as true, the representation of the expression, instead of being sent to the output buffer , is returned and can be used by the code, as in :

file_put_contents("log.txt", var_export($expression, true));

var_export is especially useful for the questions here in Stack Overflow, when the user wants to show what a representation of an expression is that can be used by other users in compiling the answer.

    
11.10.2017 / 12:56
1

In fact almost all printing options have been dissected in Difference between var_dump and print_r and echo or print, what really is the best option? .

Then var_export() does the same as print_r() in a format one little different. The result is a valid PHP code and can even be used to evaluate as code and create some execution (do not do this at run time, at most for a script of

11.10.2017 / 12:58