Search code examples
phparrayscallbackarray-map

find all the negative numbers in the array using array_map php


I have this test array

$test = array(-10,20,40,-30,50,-60);

I want the output to be

$out = array (-10, -30, -60);

Here's my solution:

$temp = array();

function neg($x)
{
    if ($x <0) 
    {
        $temp[] = $x; 
        return $x;
    }
}
$negative = array_map("neg", $test);

when I print $negative, I get what I wanted but with some entries that are null. Is there anything I can do in the callback function to not log the null entries?

Array
(
    [0] => -10
    [1] => 
    [2] => 
    [3] => -30
    [4] => 
    [5] => -60
)
1

When I print the $temp array, I thought I would get my answer but it printed an empty array. I don't understand why, I'm clearing adding the $x to the $temp[] array in my callback function. Any thoughts?

print_r($temp);
// outputs
Array
(
)
1

Solution

  • array_map will return the value when the condition satisfies and return NULL if conditions fails. In this case you can use array_filter.

    $test = array(-10,20,40,-30,50,-60);
    
    $neg = array_filter($test, function($x) {
        return $x < 0;
    });
    

    Output

    array(3) {
      [0]=>
      int(-10)
      [3]=>
      int(-30)
      [5]=>
      int(-60)
    }
    

    And if you continue to use array_map then I would suggest apply array_filter once when it is done -

    $negative = array_map("neg", $test);
    $negative = array_filter($negative);
    

    The output will be same.