4. PHP Variable Variables
There have been several cases when I needed to access a dynamic variable (where the variable name changed). You can do this easily in PHP by using what is called Variable Variables. Take a look at this example:
<?php $var1 = 'nameOfVariable'; $nameOfVariable = 'This is the value I want!!!'; echo $$var1;
5. Use Arrays in Form Fields
Not only can you create a form field that creates an element in an array (like
name['firstname']), but you can create dynamic arrays as well. This is especially useful in checkboxes, where the user could check multiple options. Take a look at this HTML:
<label><input type="checkbox" name="hobbies" value="Sports" /> Sports</label><br /> <label><input type="checkbox" name="hobbies" value="Hiking" /> Hiking</label><br /> <label><input type="checkbox" name="hobbies" value="Swimming" /> Swimming</label><br /> <label><input type="checkbox" name="hobbies" value="Swimming" /> Watching Movies</label><br />
When the above fields are posted to a PHP page, each hobby is added to the
hobbiesarray. You can then loop through that array and access each value that was checked.
6. PHP Output Buffering
I have come across cases where something was being output to the screen that I didn’t want (at least at that point, or maybe not at all).
A common example of this is if you have a function or a script that echoes out a string, but you are using the code in that instance where you don’t want it to print to the screen at that point (when using a template system or framework system, for example). In this case you would still want to be able to reuse the code, but just prevent anything from being printed out at that exact point.
This will make more sense if you look at this simple example:
<?php ob_start(); echo 'Print to the screen!!!'; $getContent = ob_get_contents(); ob_end_clean(); // Do whatever you want... // Do something with the printed content (only if you want)... echo 'Now: ' . $getContent;
You probably were familiar with at least some of these, but I hope that someone will find this list useful in some capacity. 🙂