Skip to content

PHP Tutorial PHP Syntax and Output

PHP Code Blocks

Lesson 19 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

A code block is a group of statements wrapped in curly braces { }. Blocks belong to things like if, loops and functions.

index.php
PHP
<?php
$score = 82;

if ($score >= 50) {
    echo "You passed.\n";
    echo "Well done!";
}
Output
OUTPUT
You passed.
Well done!

Both echo lines run only when the condition is true. The braces tell PHP where the block starts and ends.

Always use braces

PHP allows a single statement without braces, but it leads to bugs when someone adds a second line later.

index.php
PHP
<?php
$logged = false;

// Risky: only the first echo belongs to the if
if ($logged)
    echo "Welcome back\n";
    echo "Your balance: 100\n";
Output
OUTPUT
Your balance: 100

The second echo looks like it belongs to the if, but it does not. Braces make the intent clear and prevent this kind of mistake.

Alternative syntax for templates

When PHP and HTML are mixed, a closing } far away from its opening { is hard to find. PHP offers a different style: replace { with a colon and } with endif;, endforeach;, endfor; or endwhile;.

index.php
PHP
<?php $items = ["Pen", "Book"]; ?>
<?php if (count($items) > 0): ?>
  <ul>
    <?php foreach ($items as $item): ?>
      <li><?= $item ?></li>
    <?php endforeach; ?>
  </ul>
<?php else: ?>
  <p>Your cart is empty.</p>
<?php endif; ?>

This reads like HTML with tags. WordPress themes use this style often.

lightbulb
Where to use which
Use curly braces in pure PHP files. Use the alternative syntax in HTML templates where PHP and HTML are mixed.