trying to transfer one array with a combination of positive and negative numbers to a new array- but only where the elements are positive.
This is what I have so far:
try:
$param = array(2, 3, 4, -2, -3, -5);
$positive = array_filter($param, function ($v) {
return $v > 0;
});
print_r($positive);
http://codepad.viper-7.com/eKj7pF
What you are looking for is a filter on your array (http://www.php.net/manual/en/function.array-filter.php)
This will remove the values in the array that do not furfill your needs. A basic example would be:
function is_positive($number) {
return is_numeric($number) && $number >= 0;
}
$values = array(1, 5, -4, 2, -1);
$result = array_filter($values, 'is_positive');
print_r($result);
-- Why your function does not work:
You are returning a value. Inside a function a return will stop, because the answer is found. Thus returning the first positive number it finds in the array.
$param = array(-1,2-,3,1,2,4,-1337);
function positive_function($arr)
{
$temp = array();
foreach ($arr as &$value)
{
if($value > 0)
{
$temp[] = $value
}
}
return $temp;
}
Your function just returned the first positive value.
You have to create a new array, to hold all the positive values and return this array, after the foreach
loop run through all values.
function positive_function($arr) {
$result = array();
foreach ($arr as &$value) {
if($value > 0) {
$result[] = value;
}
}
return $result;
}
Another option would be to apply a mapping function like shown by @Yoshi. This depends, whether you need to keep the old array or just want to modify it by deleting all not-positive values.