Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHP - Colon Syntax

PHP

The colon syntax can be useful when in project views/partials where you are mixing html and php. Below are some examples for quick reference.

If statements

<?php if ($a == 5): ?>
A is equal to 5
<?php elseif ($a == 6): ?>
A is equal to 6
<?php endif; ?>

While Loops

<?php while ($i <= 10): ?>
<tr>
    <td><?php print $i; $i++ ?></td>
</tr>
<?php endwhile; ?>

For Loops

The following will create 10 table cells numbered 1 to 10.

<?php for ($i=1; $i<=10; $i++): ?>
<tr>
    <td><?= $i; ?></td>
</tr>
<?php endfor; ?>

Switch Statements

You can use colon syntax with switch statements but you (or someone else) are likely to break it later, accidentally with whitespace, so I'm not putting an example here.

References

Last updated: 16th September 2021
First published: 16th August 2018

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch