Voting

: eight minus two?
(Example: nine)

The Note You're Voting On

Mahn
10 years ago
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.

<< Back to user notes page

AltStyle によって変換されたページ (->オリジナル) /