This question already has an answer here:
I'm trying to remove all negative integers from the following array :
$array = array([-122,121,-124,124,-121,122,-122,124,-121,124,-122,125,-121,121,-123,122,-124,120]);
I've tried the following, it's not working as I don't really understand how array_filter
works :
function positive($var) {
if ($var >= 0) {
return $var;
}
}
print_r(array_filter($array, positive($var)));
How would I send each value to the positive
function? Or is there a better way of doing this? array_walk
or array_map
maybe?
</div>
Use this code:
<?php
$array = array([-122,121,-124,124,-121,122,-122,124,-121,124,-122,125,-121,121,-123,122,-124,120]);
function positive($var)
{
if ($var >= 0)
{
return true;
}
}
print_r(array_filter($array[0], 'positive'));
You had to pass $array[0]
as parameter to modify array. You have declared array with array in first element array([-122,...,-124,120]);
so to filter array you need to pass $array[0]
.
Output is:
Array ( [1] => 121 [3] => 124 [5] => 122 [7] => 124 [9] => 124 [11] => 125 [13] => 121 [15] => 122 [17] => 120 )
The PHP Documentation states:
array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.
Use a callback that tests for a positive value:
$array = [-122,121,-124,124,-121,122,-122,124,-121,124,-122,125,-121,121,-123,122,-124,120];
$positive_integers = array_filter($array, function($value) {
return $value > 0;
});