Why does print_r print before echo?

5

I have the following array :

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

Output:

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

If I print with echo before print_r :

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

Output:

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

If I print concatenating, print_r is printed before:

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

Output:

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

Still, print this 1 in front of primeiro .

Why does this happen? What is this 1 ?

    
asked by anonymous 07.05.2018 / 18:46

1 answer

8

Because print_r returns before:

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

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

Because it returns 1 :

According to the print_r documentation:

  

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

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

    
07.05.2018 / 19:04