Something simple that Php developers can learn from Javascript

I have coded in Php for 16 odd years. I thought I knew it all.

But ‘all’ I mean everything that you would use in practice.

In the middle of this year I was introduced to JavaScript, specifically via AngularJS.

Now, I used to think JavaScript was a bit of a joke language. Something you did browser side to add a bit of animation, some form validation or some other functionality that you have cut and pasted from StackOverflow, however I was wrong.

Javascript has this very, very nice library called Underscore.

Underscore means you never need to write a foreach loop ever again.

And yes, this awesome library has been ported to Php.

Lets check it out:

You call Underscore with the __ statement, add a couple of colons and then the function name. So to call each you write __::each().

From there you pass in your array and then call a anonymous function ergo:

__::each($my_array, function($item) {
// do stuff with $item

The most common functions are each and map. You also will find filter to be useful.


__::each(array(1, 2, 3), function($num) { echo $num . ','; }); // 1,2,3,

$multiplier = 2;
__::each(array(1, 2, 3), function($num, $index) use ($multiplier) {
echo $index . '=' . ($num * $multiplier) . ',';
// 0=2,1=4,2=6,


__::map(array(1, 2, 3), function($num) { return $num * 3; }); // array(3, 6, 9)

__::map(array('one'=>1, 'two'=>2, 'three'=>3), function($num, $key) {
return $num * 3;
// array(3, 6, 9);


__::filter(array(1, 2, 3, 4), function($num) { return $num % 2 === 0; }); 
// array(2, 4)

It is well worth checking out and challenging yourself to not write a loop in Php for 30 days!

A single golf clap? Or a long standing ovation?

By clapping more or less, you can signal to us which stories really stand out.