Skip to content
PHP Logo

Why is it necessary to use parentheses when combining strings and performing addition in PHP?

When combining strings and performing addition in PHP, it is necessary to use parentheses to explicitly define the order of operations. This is because PHP follows the rules of operator precedence, and without parentheses, the addition operator (+) will be evaluated before the string concatenation operator (.) leading to unexpected results.

php
// Example of using parentheses to combine strings and perform addition in PHP
$string1 = "Hello";
$string2 = "World";
$number = 2022;

// Using parentheses to ensure correct order of operations
$result = $string1 . " " . $string2 . " " . ($number + 10);

echo $result; // Output: Hello World 2032