Question:
I have 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 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
Also, print that 1
in front of the primeiro
.
Why does it happen ? What is this 1
?
Answer:
Because print_r
returns before:
print_r
returns a value. Because of this, echo
waits for all operations within its parameters before executing in order to print the value that print_r
returned.
This would be analogous to doing a mathematical operation inside echo
: first you solve the operation inside, and then demonstrate the value.
Because it returns 1
:
According to the print_r
documentation:
When the return parameter is TRUE, this function will return a string. Otherwise, the returned value will be TRUE.
Since the return
parameter has not been defined, and it is FALSE by default, the print_r
function is returning TRUE. This is converted to "1"
within echo
.