Copy PHP Array where elements are positive

后端 未结 4 1645
借酒劲吻你
借酒劲吻你 2021-01-26 22:24

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:

相关标签:
4条回答
  • 2021-01-26 22:54

    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

    0 讨论(0)
  • 2021-01-26 22:56

    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.

    0 讨论(0)
  • 2021-01-26 23:00
    $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;
    }   
    
    0 讨论(0)
  • 2021-01-26 23:07

    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.

    0 讨论(0)
提交回复
热议问题