<?php
/**
* Extract values from an array, and return the results
*
* @param array $array The array to filter
* @param callable|string $callback Function to filter the array with
*
* @return array A new array containing the filtered elements
*/
function array_excise(array &$array, callable|string $callback): array {
$result = [];
if (!is_callable($callback)) {
return $result;
}
foreach ($array as $key => $value) {
if (call_user_func($callback, $value)) {
$result[$key] = $value;
unset($array[$key]);
}
}
return $result;
}
/*
$people = [
["name" => "Billy Jean", "filter" => false],
["name" => "Ronald Reagan", "filter" => true],
["name" => "Bill Clinton", "filter" => true],
["name" => "Michael Jackson", "filter" => false],
["name" => "Johnny Cash", "filter" => false],
];
$presidents = array_excise($people, function($p){ return $p["filter"]; });
var_export(compact(['people', 'presidents']));
*/
$numbers = [
[1, 1, 1],
[1, 1, 0],
[1, 0, 0],
[0, 0, 0]
];
$noZeros = array_excise($numbers, 'array_product');
var_export(compact(['numbers', 'noZeros']));
preferences:
26.54 ms | 406 KiB | 5 Q