PHP does not have a native "clamp" (or range constraint) function(1).
As always, there are several ways to resolve this problem.
This repo contains several variations that all achieve the same thing: clamp a given value between a given maximum and minimum range.(2)
The question is: which one has your preference and why?
It is important to note that there is no right or wrong answer, all of the implementations are fully functional. the goal is not to see which variation is more popular but to gain an understanding of why a developer prefers one over the other.
When judging code, developers tend to look at the following things(3):
- Amount of code
- Code complexity
- Execution speed
- Fault tolerance (being bug free)
- Readability
Of these, only "Readability" is subjective. Complexity, fault tolerance, speed and size can all be measured.
- Full details on ammount of code can be found here.
- Full details on execution speed can be found here.
- Full details on code complexity can be found here.
To reduce the feature scope to the absolute minimum, the code in the functions is assumed to be low-level code. Validation, type coersion, etc are considered out of scope for the sake of this discussion.
At the point clamp
is called:
$value
,$min
and$max
are all assumed to be integers$min
is assumed to be smaller than$max
Footnotes
- Although one is proposed for PHP8+
- To avoid the order of the files causing a bias, the filenames contain a partial MD5 hash of their content.
- Let me know if I missed anything
clamp.832b9c44.php for me: intent is cleaner, and has a simpler phi representation, which means easier to optimise for future compiler versions