Simplify your coding - string handling in HTML & PHP

Published on
7,984 Points
2 Endorsements
Last Modified:
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";

Open in new window

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";

Open in new window

This clearly eliminates a number of sources of confusion by removing the need to escape double quotes, removes the need to use concatenation characters and makes it much easier to match HTML (single) quotes up and it allows variable substitution to function as well. Of course, a problem occurs if you are using javascript in the HTML and the javascript requires parameters to be passed. In this situation the escaped double quotes are back, but their effect is minimal compared to the chaos that can ensue if everything was double quoted. So to extend our example a little further
echo "<input name='$someName' onmouseup='javascript:aFunc(\"prm1\",\"prm2\");' type='input' value='$someValue'>\n";

Open in new window

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.
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Get 7 days free