2

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
5
  • 3
    you don't want array_map... you want array_filter Commented Aug 20, 2015 at 5:01
  • @Orangepill however it's not the concern with array_map right? I'm storing my value $x in a $temp array that is accessible within the callback function. Commented Aug 20, 2015 at 5:02
  • 1
    See Example here Commented Aug 20, 2015 at 5:04
  • The scope of $temp is with in the callback. Commented Aug 20, 2015 at 5:07
  • why is it so? I declared the $temp outside my callback and I'm appending $x to $temp everytime the callback is called.? Commented Aug 20, 2015 at 5:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is great, answers one of my questions, but why the $temp array is not getting populated in my callback function?
$temp is only available inside the function because of the scope. You can't access them like that. Though the $temp is no needed anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.