Tuesday, January 27, 2009

Mootools $A function in PHP (with a little extra 'force')

As you may have seen I'm a big of the mootools js library. I really love their $ functions as the are pretty handy in mostly every situation.

But half of my programming time I'm working with the server-side mostly in PHP and sometimes there are situations where I would love to have this handy functions in my toolbox.

So here comes one of them the $A functions which acts the quite the same as in mootools and has one thing extra, the 'force' option.

function A($var, $force=false){
return ($force || !is_array($var) ? array($var) : $var);
}
It checks if the variable is an array if yes than it returns the unchanged variable if not it wraps the variable in a new array. The force option bypass this test and wraps the variable in a new array even if it is already an array. That's all, simple but powerful.

Usage:

//Without forcing
$var1 = 'hello world';
$var1 = A($var1);
//$var1 is wrapped => array('hello world')

$fruits = array('apple', 'banana', 'cherry');
$fruits = A($fruits);
//$fruits is unchanged => array('apple', 'banana', 'cherry')

//With forcing
$fruits = A($fruits, true);
//$fruits is wrapped => array(array('apple', 'banana', 'cherry'))
It helped me a lot and maybe it can help you too.

0 comments:

Post a Comment