Readable PHP script
I’ll show the main rules that should be followed when you write the script. The main advantage of the readable code is simplicity of search and error recovery. I want to mention that some examples are marked as “incorrect”, but it doesn’t mean that they don’t work; it means that they are incorrect in the view of developing of the readable code.
1. Take the variables out of the brackets
Every time when you output the text variables in the string should be taken out of the brackets.
Incorrect example:
echo "Value is $val"
Correct example:
echo "Value is ".$val
2. Use comments
Every function should be described with some comment. Every fragment you consider to be enough complicated should have little comment. The type of the comment you can choose yourself. It can be either one text line, or block of the strings that contains the description about function or information about author etc.
3. Use the brief variant of the echo function
For example the following log
<?php
echo $val
?>
can be substituted for
<?=$val?>
4. Try to take large HTML bocks out of the php constructions. Don’t abuse the php function.
Incorrect example:
<?php
for ( $i = 1; $i < 10; $i++ ) {
echo "Number is ".$i;
echo "<br>";
echo "Number before is ".($i - 1);
echo "<br>";
}
?>
Correct example:
<?php
for ( $i = 1; $i < 10; $i++ ) {
?>
Number is <?=$i?>
<br>
Number before is <?=($i-1)?>
<br>
<?php
}
?>
Here we have two php constructions and the HTML text is situated between them. Probably, in that example you can’t see the advantages of the text taking out of the php construction bounds but if you deal with tables given rule will help you.
5. Code should be aligned according to the blocks.
Incorrect example:
<?php
for ($i = 1; $i < 10; $i++)
{
echo $i;
$j++;
}
?>
Correct example:
<?php
for ($i = 1; $i < 10; $i++) {
echo $i;
$j++;
}
?>
6. Try to simplify the complicated constructions.
Incorrect example:
$res = mysql_result(mysql_query("SELECT Num FROM db"), 0, 0)
Correct example:
$query = mysql_query("SELECT Num FROM db");
$res = mysql_result($query, 0, 0);
7. Use more spaces and empty lines.
Incorrect example:
<?php
for ($i=1; $j<10; $i++) {
$sum=$sum+$i;
$j++;
}
?>
Correct example:
<?php
for ( $i = 1; $j < 10; $i++ ) {
$sum = $sum + $i;
$j++;
}
?>
8. Use brief variants of the mathematical and string operations.
Remember that +1 can be replaced with ++, +n with +=n
Examples of the replacements:
$i = $i + 1 equals $i++
$i = $i - 1 equals $i--
$i = $i + $n equals $i+=$n
$i = $i."hello" equals $i.="hello"



