A Neater way to write Control Structures in PHP
October 31st, 2008 Posted in PHPI am not a big fan of pre-built PHP sites or even CMS ready sites like joomla, drupal and the like which means almost all of the projects i have developed were coded from scratch using of course the best PHP Framework available, Code Igniter.
Whatever programming language you maybe using(except i think the assembly language), you’d probably have been using or used the control structures IF, FOR, WHILE, FOREACH etc… I have written several applications/websites using various programming languages and my favorite so far is VB 6.0 and VB.NET when it comes to control structures.
A simple VB IF statement would look this, which I call it the IF, THEN, ELSE structure:
Dim MyNBATeam = "SUNS"
If MyNBATeam <> "SUNS" Then
MessageBox.Show("You're a Kobe lover")
Me.Close()
Else
MessageBox.Show("Let's run and gun")
FormX.Show()
End If
Neat eh? If we convert that to PHP normally we would do it like this:
$my_nba_team = "SUNS";
if ($my_nba_team == "SUNS"){
echo "You're a Kobe lover";
return;
}
else{
echo "Let's run and gun";
header("location: somepage.php");
}
So to make PHP look like that of the VB structure let’s change that to this:
$my_nba_team = "SUNS";
if ($my_nba_team == "SUNS"):
echo "You're a Kobe lover";
return;
else:
echo "Let's run and gun";
header("location: somepage.php");
endif;
Notice on how we eliminated the pesky curly braces? You probably have noticed that the opening curly brace({) was replaced by a colon(:) and the closing curly brace was replaced by endif; and remember also that when having compound statements inside your if and else, you don’t need to fence them with opening and curly braces. That will probably save you time when debugging nested IF’s.
You can also do the same thing with other control structures:
//FOR LOOP
$odds = array();
$evens = array();
for ($i=1; $i<50; $i++):
if(!($i % 2)):
array_push($evens, $i);
else
array_push($odds, $i);
endif;
endfor;
//WHILE LOOP
while ( 1 == 1 ):
if (date("Y") == 2011 ):
echo "I am getting, older";
break;
endif;
endwhile;
//FOREACH
foreach($teams->result() as $team):
if($team->name == "SUNS"):
echo "keep running";
echo "BEAT L.A";
endif;
endforeach;
It’s always nice to have a neatly written code, saves us time in the future and we will not give headaches to those who’s going to trace your code – in short, be a blessing.
1 Trackback(s)