note 118172 added to function.array-map
| From: | Mahn | Date: | Tue, 20 Oct 2015 17:10:21 +0000 |
| Subject: | note 118172 added to function.array-map | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-203987@lists.php.net to get a copy of this message | ||
You may be looking for a method to extract values of a multidimensional array on a conditional basis
(i.e. a mixture between array_map and array_filter) other than a for/foreach loop. If so, you can
take advantage of the fact that 1) the callback method on array_map returns null if no explicit
return value is specified (as with everything else) and 2) array_filter with no arguments removes
falsy values.
So for example, provided you have:
<?php
$data = [
[
"name" => "John",
"smoker" => false
],
[
"name" => "Mary",
"smoker" => true
],
[
"name" => "Peter",
"smoker" => false
],
[
"name" => "Tony",
"smoker" => true
]
];
?>
You can extract the names of all the non-smokers with the following one-liner:
<?php
$names = array_filter(array_map(function($n) { if(!$n['smoker']) return
$n['name']; }, $data));
?>
It's not necessarily better than a for/foreach loop, but the occasional one-liner for trivial
tasks can help keep your code cleaner.
----
Server IP: 72.52.91.14
Probable Submitter: 46.5.130.76
----
Manual Page -- http://php.net/manual/en/function.array-map.php
Edit -- https://master.php.net/note/edit/118172
Del: integrated -- https://master.php.net/note/delete/118172/integrated
Del: useless -- https://master.php.net/note/delete/118172/useless
Del: bad code -- https://master.php.net/note/delete/118172/bad+code
Del: spam -- https://master.php.net/note/delete/118172/spam
Del: non-english -- https://master.php.net/note/delete/118172/non-english
Del: in docs -- https://master.php.net/note/delete/118172/in+docs
Del: other reasons-- https://master.php.net/note/delete/118172
Reject -- https://master.php.net/note/reject/118172
Search -- https://master.php.net/manage/user-notes.php