Skip to content
PHP Logo

How can PHP variables be output in a template file instead of using echo statements?

To output PHP variables in a template file without using echo statements, you can use PHP's alternative syntax for control structures, such as foreach loops or if statements, to display the variables within the HTML markup. This approach helps separate the presentation logic from the PHP code, making the template file cleaner and easier to maintain.

php
<?php
// Sample PHP variables
$name = 'John Doe';
$age = 30;
$city = 'New York';

// Template file with PHP variables output
?>
<!DOCTYPE html>
<html>
<head>
    <title>User Profile</title>
</head>
<body>
    <h1>User Profile</h1>
    <p>Name: <?php echo $name; ?></p>
    <p>Age: <?php echo $age; ?></p>
    <p>City: <?php echo $city; ?></p>
</body>
</html>