A code block is a group of statements wrapped in curly braces { }. Blocks belong to things like if, loops and functions.
<?php
$score = 82;
if ($score >= 50) {
echo "You passed.\n";
echo "Well done!";
}
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.
<?php
$logged = false;
// Risky: only the first echo belongs to the if
if ($logged)
echo "Welcome back\n";
echo "Your balance: 100\n";
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;.
<?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.