I\'ve been programming in PHP for years now, but I\'ve never learned how to use any shorthand. I come across it from time to time in code and have a hard time reading it, s
One of my favorite "tricks" in PHP is to use the array union operator when dealing with situations such as functions that take an array of arguments, falling back on default values.
For example, consider the following function that accepts an array as an argument, and needs to know that the keys 'color', 'shape', and 'size' are set. But maybe the user doesn't always know what these will be, so you want to provide them with some defaults.
On a first attempt, one might try something like this:
function get_thing(array $thing)
{
if (!isset($thing['color'])) {
$thing['color'] = 'red';
}
if (!isset($thing['shape'])) {
$thing['shape'] = 'circle';
}
if (!isset($thing['size'])) {
$thing['size'] = 'big';
}
echo "Here you go, one {$thing['size']} {$thing['color']} {$thing['shape']}";
}
However, using the array union operator can be a good "shorthand" to make this cleaner. Consider the following function. It has the exact same behavior as the first, but is more clear:
function get_thing_2(array $thing)
{
$defaults = array(
'color' => 'red',
'shape' => 'circle',
'size' => 'big',
);
$thing += $defaults;
echo "Here you go, one {$thing['size']} {$thing['color']} {$thing['shape']}";
}
Another fun thing is anonymous functions, (and closures, introduced in PHP 5.3). For example, to multiple every element of an array by two, you could just do the following:
array_walk($array, function($v) { return $v * 2; });