What’s the difference between echo, print, var_export in PHP?

Asked

Viewed 792 times

4

2 answers

4


As for the comparison between echo and print:

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

Such a difference has already been discussed here:

What’s the difference between print and echo in PHP

echo or print, which really is the best option?

var_export

Already the var_export fits more in the same category of var_dump and print_r, generally used to debug. Its use 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. Valid representation means 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 outputs 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, rather than being sent to the buffer is returned and can be used by the code, as in:

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

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

2

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

Then the var_export() does the same as the print_r() in a slightly different format. The result is valid PHP code and can even be used to evaluate as code and create some execution (do not do this at runtime, at most for a script of scaffolding or something like that).

An important difference is that it will have a problem if one element references another element (or the same) within this array. He will go into loop.

It is possible to play a result in a variable instead of printing the result as in print_r(), but not in the var_dump().

Unlike the var_dump() only the data and not the details of the array.

Example of leaving it:

array (
    0 => 1,
    1 => 2,
    2 => 
    array (
        0 => 'a',
        1 => 'b',
        2 => 'c',
    ),
)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.