Copy PHP Array where elements are positive

2020-04-19 03:13发布

问题:

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:

$param = array(2, 3, 4, -2, -3, -5);

function positive_function($arr) {
    foreach ($arr as &$value) {
        if($value > 0)
            return $value;
    }
}

$modParam1 = positive_function($param);

var_dump($modParam1);

I think I have something wrong with the foreach statement, any sage advice here?

回答1:

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



回答2:

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.



回答3:

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.



回答4:

$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;
}   


标签: php arrays