Monday, July 6, 2009

PHP Shortcut of the Day

Normally in PHP you concatenate two strings like this:

$str1 = $str1.$str2;

This adds $str2 to the end of $str1. Here's a handy shortcut, which when constructing really huge XML strings is highly useful:

$str1 .= $str2;

The "dot-equals" operation is even smart and will let you concatenate to a null string at the beginning, which is a good thing when you are in loops. You can't do that in C ; you have to StrCopy and then StrCat. To me, this type of thing is what makes PHP great.

Here's another great PHP shortcut: the 'foreach' loop.

A foreach loop lets you loop through all the elements of an array and get access to either the individual keys and individual data elements. The syntax is:

foreach( $somearray as $key => $data ) { .... }

For multidimensional arrays you can nest foreach loops. It takes some getting used to this funny syntax, but it is very useful and worth knowing about.

No comments:

Post a Comment