Reputation: 3702
surprisingly these are different and I cannot understand what is going on:
var_dump(print'2');
echo "<br>";
var_dump((print '2')+3);
echo "<br>";
var_dump(print '2'+3);
echo "<br>";
echo '1'.(print '2')+3;
here is the output:
2int(1)
2int(4)
5int(1)
214
I know that print function outputs a string and this string is a number so it it showing me an integer as a value but I don't exactly understand what's happening here would someone please explain it? why +3 doesn't affect in line 2? why the vardump amount is different?
Upvotes: 0
Views: 55
Reputation: 212442
For line #1
print '2'
prints 2
and returns a 1
value that is then var_dumped() as int(1)
For line #2
print '2'
prints 2
and returns a 1
value that is then added to 3
before being var_dumped() as int(4)
For line #3
print '2'+3
prints 5
(the sum of 2
and 3
) and returns a 1
value that is then var_dumped() as int(1)
for line #4
(print '2')
prints 2
and returns a 1
which is added to 3
giving 4
; the echo then outputs 1
followed the result of that sum (4
)
Upvotes: 0
Reputation: 27855
Refer the php docs for print
Print outputs the argument passed to it and always returns 1.
So below outputs are
var_dump(print'2');
// outputs two and gives int 1 to vardump
var_dump((print '2')+3);
// outputs 2 and adds 3 to retuned 1 to pass 4 to vardump
var_dump(print '2'+3);
//prints 2+3=5 and gives 1 to var_dump
echo '1'.(print '2')+3;
// prints 2 first then 1 is concatinated with 4 which is sum of 3 and 1 from print
Upvotes: 1
Reputation: 20486
According to the documentation, print
:
Returns 1, always.
To your examples:
var_dump(print'2');
will print the string 2
and return/dump the integer 1
.var_dump((print '2')+3);
will print the string 2
and return/dump the integer 1
+ 3
.var_dump(print '2'+3);
will print '2' + 3
, which evaluates to 5
, and then return/dump the integer 1
.echo '1'.(print '2')+3;
will print 2
and then echo 1
concatenated with sum of 1
, from print '2'
, and 3
.Upvotes: 1