I came across the range function a few months ago, and it has saved so many lines of repetitive code. I got so tired of using for loops to do the most simple things.
Check out a few examples to see how this function can make your life so much easier.
Print all numbers from a to z:
foreach(range('a', 'z') as $letter) { echo $letter; }
Print all numbers from 0 to 12
foreach(range(0, 12) as $number) { echo $number; }
Print all numbers from 0 to 100, but only showing every 10th one.
foreach(range(0, 100, 10) as $number) { echo $number; }
Before I knew about Smarty, I developed me own way of having HTML templates for the projects I developed. Admittedly, I still use it even though Smarty is so much more powerful. When I don’t need the versatility of Smarty, I just use my own method.
I started off by having a template directory with HTML files in it. These files consist of all the HTML code I want, and has placeholders to where content will be.
<html> <body> <div>%header%</div> <div> <div>%menu%</div> <div>%content%</div> </div> <div>%footer%</div> </body> </html>
As you can see, I have 4 place holders there, %header%, %menu%, %content% and %footer.
Now all I have to do is use str_replace to replace the place holders with content.
Here is an example of doing that
$html = file_get_contents("template.html"); $menu = "<ul><li>Option 1</li><li>Option 2</li></ul>"; $header = "<h1>This is the Header</h1><br />%menu%"; $content = "<p>This is some content.</p>"; $footer = "<small>This is the footer</small>"; $html = str_replace("%header%",$header,$html); $html = str_replace("%menu%",$menu,$html); $html = str_replace("%content%",$content,$html); $html = str_replace("%footer%",$footer,$html); echo $html;
As you can see, I make use of the placeholder within another placeholder as well. So the %menu% is also replace within the $header variable. Just note if you want to use it like that, you need to order the str_replace so that it will get replaced.
The resulting HTML will be:
<html> <body> <div><h1>This is the Header</h1><br /><ul><li>Option 1</li><li>Option 2</li></ul></div> <div> <div><ul><li>Option 1</li><li>Option 2</li></ul></div> <div><p>This is some content.</p></div> </div> <div><small>This is the footer</small></div> </body> </html>