Using Alternative Syntax for Control Structures in PHP to Enhance HTML Integration
Md Mahabur Rahman Nadim
To building a secure web application for clients | Let's Connect!
When using PHP to mix HTML and PHP code, you can improve readability by employing the alternative syntax for control structures. Instead of curly braces({}), you replace the opening curly braces with a colon (:). For the closing curly braces, simply replace them with the end followed by the control structure's name and a semicolon (;) like (endif; endfor; endwhile;). in the middle just replace only opening curly braces with colon(:) Don't replace closing curly braces with end keyword. This alternative syntax makes your PHP templates more concise and easier to understand. Below I give some example which help you to understand it better.
If|elseif|else conversion
$a = 10;
if($a == 10){
echo "a is equal to 10";
}elseif($a == 11){
echo "a is equal to 11";
}else{
echo "a is not equal to 10 or 11";
}
// let convert it into alternative syntax
if($a == 10):?>
<h1> A (<?=$a?>) is equal to 10</h1>
<?php elseif($a == 11):?>
<h1> A (<?=$a?>) is equal to 11</h1>
<?php else:?>
<h1> A (<?=$a?>) is not equal to 10 or 11</h1>
<?php endif;?>
While Loop
<!-- while loop -->
<?php
$i = 0;
while($i < 10){
echo $i . "<br>";
$i++;
}
// convert it into alternative syntax
$i = 0;
while($i<10):?>
<h3>The number is <?=$i?></h3>
<?php $i++; endwhile;?>
For loop
领英推荐
<!-- for loop -->
<?php
for($i = 0; $i < 10; $i++){
echo $i . "<br>";
}
// convert it into alternative syntax
for($i = 0; $i < 10; $i++):?>
<h3>The number is <?=$i?></h3>
<?php endfor;?>
Foreach loop
<!-- foreach loop -->
<?php
$arr = [1,2,3,4,5,6,7,8,9,10];
foreach($arr as $value){
echo $value . "<br>";
}
// convert it into alternative syntax
foreach($arr as $value):?>
<h3>The number is <?=$value?></h3>
<?php endforeach;?>
switch statement
<?php
$a = 10;
switch($a){
case 10:
echo "a is equal to 10";
break;
case 11:
echo "a is equal to 11";
break;
default:
echo "a is not equal to 10 or 11";
}
// convert it into alternative syntax
switch($a):
case 10:?>
<h3>A (<?=$a?>) is equal to 10</h3>
<?php break;
case 11:?>
<h3>A (<?=$a?>) is equal to 11</h3>
<?php break;
default:?>
<h3>A (<?=$a?>) is not equal to 10 or 11</h3>
<?php endswitch;?>