Is there a β€œclip” function in PHP?

I wrote a function to β€œclamp” numbers in PHP, but I wonder if this function exists in the language of the language.

I read the PHP.net documentation in the math section, but I could not find it.

Basically my function is that it takes a variable, an array of possible values ​​and a default value, this is my function signature:

function clamp_number($value, $possible_values, $default_value)

If $value does not match any of the $possible_values , then by default it is equal to $default_value

I think my function will be faster if PHP already provides it initially, because I often use my program.

In any case, if this question does not belong to SO, feel free to vote to close it.

+4
source share
3 answers
 $value = in_array($value, $possible_values) ? $value : $default_value; 
+5
source

It seems you are just trying to find the number inside the set. The actual clamp function will ensure that the number is within two numbers (lower bounds and upper bounds). Thus, the psudo code will clamp(55, 1, 10) will produce 10 , and clamp(-15, 1, 10) will produce 1 , where clamp(7, 1, 10) will produce 7 . I know that you are looking for more in_array methods, but for those who get here from Google, here is how you can clamp PHP without creating a function (or making it a function).

 max($min, min($max, $current)) 

For instance:

 $min = 1; $max = 10; $current = 55; $clamped = max($min, min($max, $current)); // $clamped is now == 10 

A simple clamping method would be:

 function clamp($current, $min, $max) { return max($min, min($max, $current)); } 
+16
source

This is a good question, but as far as I know, no. It would be much better (and also easy) to implement this in C as part of the standard PHP library, but no. You have to do this in user space.

+1
source

Source: https://habr.com/ru/post/1491529/


All Articles