2

I have an array as below.

$denominations = array(100, 200, 500, 1000, 5000);

And dynamic minimum and maximum value,

For example;

$minimumValue = 150;
$maximumValue = 700;

So my denomination array should eliminate 100 and 1000 above.

I know I can do it by for loop. But to simplify my coding is there any array function can do this?

3
  • "So my denomination array should eliminate 100 and 1000 above". Should eliminate 5000 as well, right? Commented Jun 15, 2015 at 11:32
  • @D4V1D yes you are right Commented Jun 15, 2015 at 11:34
  • Thanks all. Most of the answers solves my problem Commented Jun 15, 2015 at 11:49

4 Answers 4

3

Select valid items by array_filter

$minimumValue = 150;
$maximumValue = 700;

$new = array_filter($denominations, 
     function($v) use($minimumValue, $maximumValue) 
         { return ($v > $minimumValue && $v < $maximumValue); });
Sign up to request clarification or add additional context in comments.

Comments

2

array_map & array_filter can help -

$denominations = array(100, 200, 500, 1000, 5000);
$minimumValue = 150;
$maximumValue = 700;
$new = array_map(function($a) use($minimumValue, $maximumValue) {
    if($a > $minimumValue && $a < $maximumValue) {
        return $a;
    }
}, $denominations); // Will return the values if satisfied else null will be set

$new = array_filter($new); // Filter out the null values

With array_filter -

$new = array_filter($denominations , function($a) use($minimumValue, $maximumValue) {
    if($a > $minimumValue && $a < $maximumValue) {
        return $a;
    }
});

5 Comments

Delete the 1st :))))))
@splash58 There is nothing wrong with that also. This may help for other situation if required. :)
Both the answers works.. Its not a wrong to have more than one method two solve one problems ;-)
Just about This may help for other situation , I don't say it doesn't work
@splash58 Sometimes it may need to count how many are eliminated or which keys are eliminated.
1

You can simply use array_filter as

$denominations = array(100, 200, 500, 1000, 5000);
$minimumValue = 150;
$maximumValue = 700;
array_filter($denominations,function($v) use(&$result,$minimumValue,$maximumValue)
{
 if($v > $minimumValue && $v < $maximumValue) 
     $result[] = $v;
});
print_r($result);

Fiddle

Comments

1

Not tested yet but should be something like this using array_filter function:

<?php
$denominations = array(100, 200, 500, 1000, 5000);

$minimumValue = 150;
$maximumValue = 700;

$denominations = array_filter($denominations , function($key, $value) {
    return $value >= $minimumValue && $value <= $maximumValue;
}, ARRAY_FILTER_USE_BOTH)); 
?>

Comments

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.