foreach ( $fmt as $key => $val ) { if ( $p[$key] ) { $p[‘chat’] = "<$val>{$p[‘chat’]}</$val>"; } }
echo $p[‘chat’];
?>
Lets break this function down part by part and see why it is a better solution for the task at hand (bearing in mind that for other tasks the above concepts might actually be better solutions).
As I try to write and explain this I am finding it quite hard, which is strange because it is just an associative array, quite a simple construct. What I am finding hard to put into words is all the reasons why I chose this construct and constructed it in this way. There are actually quite a few reasons, most of them being subtle. Ones that come from lots of practice working with PHP and HTML.
Here are my reasons as I type them:
On the form there are four incoming variables. I want an easy way to store those variable names in my PHP script so I can easily access them.
Each of the incoming variables can evaluate to true or false. If they evaluate to true then I want to echo a value. I need a way to tie the incoming value to the echoed value.
I don’t know how many types of false/true format options I might need in the future. Therefore ideally I want to define a construct that is very easy to add new formatting options to (without altering any other code). E.g. To add a quote function all I have to do is add “quote” => “blockquote”
I know that the function foreach is one of the most useful things about PHP. I want to make use of it in this case.
During my iteration of each array element I want to be able to easily access the array key/value pairs.
Now on to the foreach loop:
foreach ( $fmt as $key => $val ) { if ( $p[$key] ) { $p[‘chat’] = "<$val>{$p[‘chat’]}</$val>"; } }
Or more specifically:
foreach ( $fmt as $key => $val )
This is an easy way to loop through each element of an array and then perform any number of actions within the following brackets. If we were to write this with sensible variable names it might make more sense:
if ( $p[‘bold’] ) <- first iteration if ( $p[‘italic’] ) <- second iteration if ( $p[‘underline’] ) <- third iteration if ( $p[‘strike’] ) <- fourth iteration
Then if the if statement were to evaluate to true all four times what we would really be saying is:
if ( $p[‘bold’] ) { $p[‘chat’] = "<b>{$p[‘chat’]}</b>"; }
Note that within the defining associative array we didn’t need to put the full HTML <b> and </b>. That is because we know that all HTML format commands have <> and </> and there is no point using redundant code.
Now that we know all of the above lets have a look at the final solution once again. It should make perfect sense!