Why doesn't array_filter() mutate my strings while it iterates?
Solution 1:
array_filter
expects true
or false
from the callback function to retain or remove the corresponding element. In your implementation, unless you have a 0
or falsey value it will always return true
. You want array_map
that actually applies the return of the callback:
$filteredShots = array_map(function($shot) {
if (is_numeric($shot)) {
return floatval($shot);
}
}, $shots);
You can also modify the original array using array_walk
:
array_walk($shots, function(&$shot) {
if (is_numeric($shot)) {
$shot = floatval($shot);
}
});
You can use array_filter
to remove non-numeric:
$filteredShots = array_filter($shots, function($shot) {
return is_numeric($shot) ? true : false;
});
//or simply
$filteredShots = array_filter($shots, 'is_numeric');