Copy PHP Array where elements are positive

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

提交回复
热议问题