<?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']));
- Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- array (
'numbers' =>
array (
1 =>
array (
0 => 1,
1 => 1,
2 => 0,
),
2 =>
array (
0 => 1,
1 => 0,
2 => 0,
),
3 =>
array (
0 => 0,
1 => 0,
2 => 0,
),
),
'noZeros' =>
array (
0 =>
array (
0 => 1,
1 => 1,
2 => 1,
),
),
)
- Output for 7.4.0 - 7.4.33
- Parse error: syntax error, unexpected '|', expecting variable (T_VARIABLE) in /in/DM36O on line 11
Process exited with code 255.
preferences:
113.04 ms | 407 KiB | 5 Q