1

I can check if some integer value (which comes from user input, and thus should be filtered) is in specific range like this:

<?php
  $size=50;
  var_dump(in_array($size,range(1,100)));
?>

which will echo true if the size in range 1 to 100. Of course the other method is using filters:

<?php
  $size=50;
  $int_options = array("options"=>
                        array("min_range"=>0, "max_range"=>256));
  var_dump(filter_var($size, FILTER_VALIDATE_INT, $int_options));
?>

But, what if I need to know if the elements of an array are in this range?(and probably remove those not) What is the best practice, considering the performance and memory usage. I prefer to use php functions instead of writing mine.

2
  • do you want to compare each array element to be in different range? Commented Jul 23, 2013 at 10:32
  • No! All elements should be checked to be in dedicated range for example 1 to 100 and ofcource I prefer the method in which data is sanitized and filtered, because the $size comes form user input. thanks Commented Jul 23, 2013 at 10:35

2 Answers 2

3

Slightly functional approach (I don't know if PHP support lambdas):

function mapper($n) { return $n >= 1 && $n <= 100 ? 1 : 0; }

...

if (array_product(array_map('mapper', $array)) == 1) { }

Not very performance nor memory efficient, though.

For removing, I'd suggest using array_filter.

function my_filter($n) { return $n >= 1 && $n <= 100; }

...

$newarray = array_filter($array, 'my_filter');

(btw, who the hell designed that language.. array_map and array_filter have different order of parameters?!)

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

3 Comments

sidenote: since PHP is originated from different language, they have different orders. Other example is in_array() and strpos(). Even crazier, order of arguments in some functions can be reversed, e.g. implode()
Thanks but that looks too expensive. I'd love some more compressed way. I have 50 of this arrays in my page
@Arash, and the second one? (array_filter). That should be cheap.
0

If I were you, I will use a more simple approach:

$size=50;
if($size <= 100 && $size >= 1) {
  return true;
} else {
  return false;
}

No function call, simple integer comparison. Good performance.

2 Comments

Thanks man but this is not my question. the question is related to array elements, and that was just the begining. As the $size comes from user input, it should be sanitized and so I prefered to use those methods
you can wrap the comparison codes into a small function, and call the function for each of your array elements.

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.