Req #71320 [Com]: Extend array_map/filter to call method on each element

From: Date: Sat, 09 Jan 2016 15:39:48 +0000
Subject: Req #71320 [Com]: Extend array_map/filter to call method on each element
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-198547@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=71320&edit=1

 ID:                 71320
 Comment by:         dharkness at gmail dot com
 Reported by:        dharkness at gmail dot com
 Summary:            Extend array_map/filter to call method on each
                     element
 Status:             Open
 Type:               Feature/Change Request
 Package:            Arrays related
 PHP Version:        5.6.17
 Block user comment: N
 Private report:     N

 New Comment:

After further consideration, perhaps this deserves new functions to avoid confusing the definition
of a callable. They would behave just like these:

    function array_map_method(array $arr, $name) {
        return $arr 
            ? array_map(function ($object) use ($name) {
                    return $object->$name();
                }, $arr) 
            : array();
    }

and

    function array_filter_method(array $arr, $name) {
        return $arr 
            ? array_filter($arr, function ($object) use ($name) {
                    return $object->$name();
                }) 
            : array();
    }

May as well add array_map_property() and array_filter_property() for completeness. :)


Previous Comments:
------------------------------------------------------------------------
[2016-01-09 15:16:27] dharkness at gmail dot com

Description:
------------
I'm finding myself writing code like the following lately:

    $titles = array_map(
        function ($book) { return $book->getTitle(); },
        $books
    );

and

    $anonymous = array_filter(
        $books,
        function ($book) { return $book->isAnonymous(); }
    );

I was initially thinking a new callable form word work, e.g. [null, 'methodName'], but
that by itself isn't callable and would not make sense when passed to other methods that accept
callable such as call_user_func. The functions would either build a real callable using each array
element or simply call the method directly on it.

    $titles = array_map([null, 'getTitle'], $books);

and

    $anonymous = array_filter($books, [null, 'isAnonymous']);



------------------------------------------------------------------------



--
Edit this bug report at https://bugs.php.net/bug.php?id=71320&edit=1


Thread (4 messages)

« previous php.bugs (#198547) next »