News Feed
Sections




News Archive
Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Giorgio Sironi's Blog:
Stop writing foreach() cycles
February 18, 2010 @ 10:58:28

Giorgio Sironi has a recommendation for developers out there - stop writing foreach loops, there's something better in PHP 5.3+ - closures

There are some array functions which have already been supported at least from Php 4, and that take as an argument a callback whose formal parameters have to be one or two elements of the array. [...] In Php 5.3, callbacks may also be specified as anonymous functions, defined in the middle of other code. These closures are first class citizens, and are treated as you would treat a variable, by passing it around as a method parameter.

He includes some code examples to show you how closures used in callbacks can replace a lot of the other looping normally done by a separate bit of code. Most of the instances are in array functions that take in a callback and apply it to each element in the array (some recursively). The last example shows how to use it in a usort call to make the custom sorting of an array simpler.

0 comments voice your opinion now!
foreach closure tutorial array callback


blog comments powered by Disqus

Similar Posts

CodeForest.net: Multilanguage support in Zend Framework

PHPBuilder.com: Creating and Manipulating PDFs with PHP and FPDF

Fabien Potencier's Blog: Tweeting from PHP

Christopher Bledsoe's Blog: PHP Dependency Injection (Inversion of Control)

PHPMaster.com: Practical Code Refactoring, Part 2 - Readability


Community Events





Don't see your event here?
Let us know!


podcast opinion refactor install symfony2 code framework laravel developer community language release threedevsandamaybe series testing list configure interview introduction unittest

All content copyright, 2014 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework