简体   繁体   中英

Actually run a function a certain percentage of the time in PHP

How can I write a function in PHP to call a given function (anonymous) X% of the time?

For example:

function call_weighted(0.1, function() {
      echo 'this is actually run approximately 10% of the times it is called';
});
function call_weighted($weight, $function) {
    if (mt_rand() < $weight * mt_getrandmax()) {
        $function();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM