On Thu, Jun 28, 2012 at 2:43 PM, Sebastian Krebs <krebs....@gmail.com> wrote: > Hi, > > Whats the difference to the (already existing) function array_map() (except > the syntax and one more new keyword)? > >> $firstNames = array_map(function($user){return $user->firstname;}, > $users); > > Don't want to rewrite every example you gave, but you probably see my point.
They are roughly the same. List comprehensions are basically a way of mapping + filtering. Their main advantage is a dedicated, more concise syntax and also the ability to combine multiple maps and filters in one expression. Also PHP is not a particularly lambda-y language in general; using array_map for that purpose would feel "wrong" to me. I'd probably rather write out a full foreach loop than use map. Generator expressions additionally bring the concept of lazy evaluation into the mix. This is useful in several situations, e.g. when processing large amounts of data, like log files. The following Python example is taken from http://www.dabeaz.com/generators/Generators.pdf: wwwlog = open("access-log") bytecolumn = (line.rsplit(None,1)[1] for line in wwwlog) bytes = (int(x) for x in bytecolumn if x != '-') print "Total", sum(bytes) The code is written as a set of simple operations, which are all defined in terms of iterating a whole file/list. But the actual execution is lazy, thus basically applying all the operations in a "pipeline". So the whole potentially multi-gig log file is never loaded into memory. The same could be done in PHP, just a different syntax :) Nikita -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php