Browse All Articles
> Simplify your coding - string handling in HTML & PHP
It should be a truism that simple, clearly written code is easier to maintain than complex and impenetratable code. Yet a common problem in PHP is that many programmers (especially those new to PHP) find some of the program code hard to read. They sometimes compound this error when mixing HTML with PHP and the chief culprit is the "double quote". It is not unusual to see code that looks like this
echo "<input name=\"$someName\" type=\"text\" value=\"$somevalue\">\n";
It is quite easy to lose a double quote somewhere and spend quite a bit of time looking for it or matching pairs. The obvious alternative is to encase the PHP string in single quotes but this affects the PHP variable substitution mechanism which then requires further workarounds. Many people believe that (X)HTML or XML requires double quotes, but the W3C standards are quite clear - either " or ' can be used.
The solution is therefore to enclose strings in double quotes and place HTML attributes in single quotes. This allows the PHP substitution mechanism to function whilst allowing HTML to have its attributes enclosed as required by the standards. Our awkward statement shown above now looks like this
echo "<input name='$someName' type='input' value='$someValue'>\n";
It is worth trying to keep your code as simple and clear as possible. Remember - if it goes wrong it will probably be you that has to edit it, so make your life as easy as possible.