Skip to content
PHP Logo

How can the PHP code be optimized for better performance and readability when dealing with variable assignments and concatenation?

To optimize PHP code for better performance and readability when dealing with variable assignments and concatenation, it is recommended to use the concatenation operator (.) instead of double quotes for simple string concatenation. Additionally, it is good practice to break down complex concatenations into smaller, more readable chunks by assigning intermediate results to variables.

php
// Inefficient way
$name = "John";
$age = 30;
$city = "New York";

$message = "Hello, my name is " . $name . " and I am " . $age . " years old. I live in " . $city;

// Optimized way
$name = "John";
$age = 30;
$city = "New York";

$intro = "Hello, my name is ";
$ageInfo = " and I am ";
$location = " years old. I live in ";

$message = $intro . $name . $ageInfo . $age . $location . $city;