Saturday, November 10, 2007

A couple cool things Volume I

I have decided to post cool findings so in case anyone ever reads this maybe they can pick up a few cool pointers.

For loops are dead in PHP, let me show you why you will almost never need a for loop again.



for($i = 0; $i <= 10; $i++) {
echo $i . ' ';
}

vs

foreach(range(1,10) as $i) {
echo $i . ' ';
}


The for loop is ugly and convoluted, and while the foreach with a range probably uses more overhead its usually not a big deal in PHP as app processor usage is usually least of your concerns. We need to move on from C people c'mon...

If you didn't notice, I didn't close the PHP (?>). That's because you don't need to! There is absolutely no reason to close it, in fact, only bad things will happen if you close it, such as accidental whitespaces (which causes weird session errors). PHP will find the EOF and stop there, it won't cause any slowdown, and has no cons.


Another thing I noticed, is a lot of sites out there don't realize how cool the label tag in XHTML/HTML is. By simply adding a tag around an input type of radio or checkbox, it allows you to select the input by clicking the text within the label tag.

Let me give you an example.


Crappy site:

<input name="name" value="123" type="checkbox"> Check

Awesome site:

<label>
<input name="name" value="123" type="checkbox"> Check
</label>



Now, see it in action for yourself....

Crappy site:
Check

Awesome site:



They are very similar, except that on the awesome site, you can actually click the text "click here" and it will select the box, or obviously you can check the box the "old-fashioned" way.

Thats all for now, more cool code-tidbits to come.