What are the best practices for optimizing PHP code, such as avoiding duplicate variable assignments and unnecessary echoes?

To optimize PHP code, it is important to avoid duplicate variable assignments and unnecessary echoes. This can be achieved by reusing variables whenever possible and only echoing output when necessary. By minimizing redundant operations, the code will run more efficiently and improve overall performance.

// Bad practice: Duplicate variable assignments and unnecessary echoes
$name = "John";
echo "Hello, " . $name . "!"; // Unnecessary echo
$greeting = "Hello, " . $name . "!"; // Duplicate variable assignment

// Good practice: Reuse variables and only echo when necessary
$name = "John";
$greeting = "Hello, " . $name . "!"; // Reuse variable
echo $greeting; // Only echo when necessary