Copy PHP Array where elements are positive

后端 未结 4 1658
借酒劲吻你
借酒劲吻你 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 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.

提交回复
热议问题