JV’s Power Tips for PHP (2) - Method 3
(Page 5 of 7 )
Here it is:
<?php
$p = &$_POST;
echo ($p[‘bold’]?”<b>”:””)
. ($p[‘italic’]?”<i>”:””)
. ($p[‘underline’]?”<u>”:””)
. ($p[‘strike’]?”<s>”:””)
. $p[‘chat’]
. ($p[‘strike’]?”</s>”:””)
. ($p[‘underline’]?”</u>”:””)
. ($p[‘italic’]?”</i>”:””)
. ($p[‘bold’]?”</b>”:””);
?> A bit more elegant? It certainly seems smaller than the previous two methods. Let’s have a detailed look at what’s going on:
Once again I used $p = &$_POST, so each time you see a $p you know it is the same as typing $_POST (but quicker).
Then the rest of the code is one long echo statement. Each part of the echo statement is a conditional statement wrapped up in () brackets. Let’s look at exactly how one of those statements works. For example:
($p[‘bold’]?”<b>”:””) Firstly lets ignore the ()’s so that it becomes:
$p[‘bold’]?”<b>”:”” What is really happening is this:
test this -> $p[‘bold’] ? output this if true -> “<b>”: output this if false -> “”; The ‘test this’ part follows the same rule as an if statement. In our case that will either be 1 (true) or nothing (false).
Then the entire thing is wrapped up in ()’s which ensures that the output is directed exactly where we want it and also helps with parsing accuracy.
This type of conditional statement can also be used on its own like so:
<?php
$your_thoughts = “i like it”;
$your_opinion = $your_thoughts == “i like it” ? “great” : “not so great”;
echo “This type of statement is $your_opinion.”;
// Output:
// This type of statement is great.
?> Of course if it was me I would put () around it so that it looked like this:
$your_opinion = ($your_thoughts == “i like it” ? “great” : “not so great”); I find that just makes this type of conditional operator easier to read and work with in general. Anyway, back to the third solution. If we look at it again it should now make perfect sense:
<?php
$p = &$_POST;
echo ($p[‘bold’]?”<b>”:””)
. ($p[‘italic’]?”<i>”:””)
. ($p[‘underline’]?”<u>”:””)
. ($p[‘strike’]?”<s>”:””)
. $p[‘chat’]
. ($p[‘strike’]?”</s>”:””)
. ($p[‘underline’]?”</u>”:””)
. ($p[‘italic’]?”</i>”:””)
. ($p[‘bold’]?”</b>”:””);
?> But is it the most elegant way of solving this problem? Not really. It suffers from the same problem that all of the above solutions do. I.E. What happens if I want to add new types of on/off formatting to this script? In all of the above solutions you would have to copy and paste redundant code. That is not very elegant. Furthermore, it would be far too easy to make a copy/paste mistake!
So let’s scrap all of the above and have another go at solving this problem.
Next: Method 4 >>
More PHP Articles
More By Justin Vincent