Why does the print_r print before the echo?

Asked

Viewed 94 times

5

I got the following array:

$array = array(10,20,30);
print_r($array);

Exit:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)

If I print with echo before the print_r:

echo 'primeiro: ';
print_r($array);

Exit:

primeiro: Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)

If I print concatenating, the print_r is printed before:

echo 'primeiro: ' . print_r($array);

Exit:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)
primeiro: 1

Still, print that one 1 in front of the primeiro.


Why does this happen? What is this 1 ?

1 answer

8


Because print_r returns earlier:

print_r returns a value. Because of this, echo awaits all operations within its parameters before executing to be able to print the value that print_r returned.

This would be analogous to doing a mathematical operation within the echo: first the operation will be solved in, then demonstrate the value.

Because it returns 1:

According to the documentation of print_r:

When the Return parameter is TRUE, this function will return a string. Otherwise, the value returned will be TRUE.

As the parameter return was not defined, and it is FALSE by default, the function print_r is returning TRUE. This is converted to "1" within the echo.

  • 2

    I think it will be interesting to say that with parameter return to true will give exactly the result that the author of the question intended, and perhaps exemplifying what it would call in this case.

Browser other questions tagged

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