note 96564 added to function.array-map
| From: | virtual dot greg at gmail dot com | Date: | Fri, 05 Mar 2010 11:07:35 +0000 |
| Subject: | note 96564 added to function.array-map | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-166696@lists.php.net to get a copy of this message | ||
PHP 5.3 enables us to use inline anonymous functions with array_map, cleaning up the syntax
slightly.
$data = array(
array('id' => 1, 'name' => 'Bob', 'position'
=> 'Clerk'),
array('id' => 2, 'name' => 'Alan', 'position'
=> 'Manager'),
array('id' => 3, 'name' => 'James', 'position'
=> 'Director')
);
$names = array_map(
function($person) { return $person['name']; },
$data
);
print_r($names);
This was possible (although not recommended) in prior versions of PHP 5, via create_function().
$names = array_map(
create_function('$person', 'return $person["name"];'),
$data
);
You're less likely to catch errors in the latter version because the code is passed as string
arguments.
These are alternatives to using a foreach:
$names = array();
foreach ($data as $row) {
$names[] = $row['name'];
}
----
Server IP: 87.124.86.46
Probable Submitter: 78.105.106.149 (proxied: 78.105.106.149)
----
Manual Page -- http://www.php.net/manual/en/function.array-map.php
Edit -- https://master.php.net/note/edit/96564
Del: integrated -- https://master.php.net/note/delete/96564/integrated
Del: useless -- https://master.php.net/note/delete/96564/useless
Del: bad code -- https://master.php.net/note/delete/96564/bad+code
Del: spam -- https://master.php.net/note/delete/96564/spam
Del: non-english -- https://master.php.net/note/delete/96564/non-english
Del: in docs -- https://master.php.net/note/delete/96564/in+docs
Del: other reasons-- https://master.php.net/note/delete/96564
Reject -- https://master.php.net/note/reject/96564
Search -- https://master.php.net/manage/user-notes.php