|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #69862 PHP function to clamp numbers
Submitted: 2015-06-17 12:32 UTC Modified: 2015-06-18 10:23 UTC
From: david dot proweb at gmail dot com Assigned: kalle (profile)
Status: Closed Package: Math related
PHP Version: 7.0.0alpha1 OS: any
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
Solve the problem:
22 + 6 = ?
Subscribe to this entry?

 [2015-06-17 12:32 UTC] david dot proweb at gmail dot com
Need a PHP function to clamp numbers, natively. Currently it is possible, but will be great if it supports natively.

    function clamp($number, $minValue, $maxValue) {
        return max($minValue, min($maxValue, $number)); 

Basically, it will return the $number if is greater than $minValue and lower than $maxValue. If $number is lower than $minValue, it returns $minValue. If $number is greater than $maxValue, it returns $maxValue.

    clamp(2, 1, 3); // => 2 (in range)
    clamp(1, 1, 3); // => 1 (in range, min value)
    clamp(3, 1, 3); // => 3 (in range, max value)
    clamp(0, 1, 3); // => 1 (out range, using min value)
    clamp(4, 1, 3); // => 4 (out range, using max value)


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2015-06-17 13:11 UTC]
I don't understand why you need this builtin.

as you can implement very easily buy just 3 lines codes
 [2015-06-17 13:16 UTC] david dot proweb at gmail dot com
@laruence there a lot PHP functions that we can implement with few lines, but PHP supports it natively. This function will help you make this natively and avoid users recreate it.
 [2015-06-17 14:05 UTC]
to be honest, "we should do it because we can, and we did similar things" is a annoying argument.

anyway, the reason why I'd like don't add this is because, I have never try to use such function before..

this is just my 2cents.
 [2015-06-18 10:23 UTC]
-Status: Open +Status: Closed -Assigned To: +Assigned To: kalle
 [2015-06-18 10:23 UTC]
I agree with Xinchen here, some functions even are simply better off being implemented in native PHP. Even some functions like atanh(), rad2deg() and so on could probably have been better of being implemented in PHP.

My best suggestion here is to make a PR and post it to the internals for some debate.
 [2017-05-05 10:38 UTC] devsmt at gmail dot com
the problem in composer/namespaces era is people rewrite this function(and similar) many times as it is needed for param validation and call it with different names, leading to duplication, waste and fatigue, although small.
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Apr 22 10:01:30 2024 UTC