note 96564 modified in function.array-map by danbrown
| From: | danbrown@php.net | Date: | Fri, 05 Mar 2010 15:21:09 +0000 |
| Subject: | note 96564 modified in function.array-map by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-166698@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.
<?php
$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().
<?php
$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:
<?php
$names = array();
foreach ($data as $row) {
$names[] = $row['name'];
}
?>
--was--
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'];
}
http://php.net/manual/en/function.array-map.php