What will be the value of $x when given statement execute?

$x = 3 + "15%" + "$25"?

Last updated 4 years, 7 months ago | 1351 views 75     5

Tags:- PHP

PHP | Statement $x = 3 + "15%" + "$25"?

The correct answer is 18.

Here’s why:

PHP is a  loosely typed language, therefore it does automatic type conversion based on the context in which a variable or value is being used.

 

If you perform an arithmetic operation on an expression that contains a string, that string will be interpreted as the appropriate numeric type for the purposes of evaluating the expression. So, if the string begins with one or more numeric characters, the remainder of the string (if any) will be ignored and the numeric value is interpreted as the appropriate numeric type. On the other hand, if the string begins with a non-numeric character, then it will evaluate to zero.

Therefore the value "15%" evaluates to the numeric value 15 and "$25" evaluates to the numeric value zero. 

So the above statement evaluated to

 $x = 3 + 15 + 0

 Which is equal to 

 $x = 18

 Please note that as of PHP 7.2, this code may throw an error.