What will be the output of the following PHP code ?
<?php
$one = "Hello";
$two = "World";
echo "$one"+"$two";
?>
<?php
$one = "Hello";
$two = "World";
echo "$one"+"$two";
?>
A. HelloWorld
B. Hello+World
C. 0
D. Error
Answer: Option C
Solution(By Examveda Team)
In the given PHP code, the concatenation operator (.
) should be used instead of the addition operator (+
) to concatenate strings. When using the addition operator with strings, PHP will attempt to convert the strings to numbers for addition. If a string cannot be converted to a number, it will be treated as 0
.So, in this code,
"$one"
and "$two"
are treated as numeric strings, which will be converted to 0
when converted to numbers. Therefore, the output of the expression "$one" + "$two"
will be 0
.Option A:
HelloWorld
is incorrect because the correct output is 0
, not the concatenation of the two strings.Option B:
Hello+World
is incorrect because the correct output is 0
, not the two strings separated by a plus sign.Option D:
Error
is incorrect because there is no syntax error in the code, but the output is 0
Join The Discussion
Comments ( 1 )
Related Questions on Operators and Expressions in php
What will be the output of the following PHP code ?
<?php
"Hello World"
?>
A. Error
B. Hello World
C. Nothing
D. Missing semicolon error
What will be the output of the following PHP code ?
<?php
print_r "Hello world"
?>
A. Error
B. Hello World
C. Nothing
D. Missing semicolon error
A. redredred
B. redred
C. red
D. Error
A. # Hello world
B. Hello world# Hello world
C. Hello world
D. Error
the answer is error
D