Skip to content

IncorrectRandomRange ​

error on by default

Group: Probable bugs · PhpStorm name: IncorrectRandomRangeInspection

rand(), mt_rand() and random_int() expect (min, max). Passing a minimum greater than the maximum is an error (random_int() throws, mt_rand() warns/returns false on older versions, rand() silently swaps). Flag calls whose bounds are known numbers in the wrong order.

Example ​

php
<?php
define('DICE_FACES', 6);

class Lottery { const LOW = 1; const HIGH = 49; }

function roll($bonus = 10)
{
    $floor = 100;
    return [
        mt_rand(9, 3),
        mt_rand(3, 9),
        rand(DICE_FACES, 1),
        rand(1, DICE_FACES),
        random_int(Lottery::HIGH, Lottery::LOW),
        \random_int($floor, -1),
        random_int($bonus, 0),
        random_int(0, PHP_INT_MAX),
        random_int(0, PHP_INT_MIN),
        random_int(7, 7),
        random_int(0x10, 1),
        mt_rand(2.5, 1),
        random_int(5, count([1])),
    ];
}

Reported:

  • line 10: Minimum is greater than maximum in this random range.
  • line 12: Minimum is greater than maximum in this random range.
  • line 14: Minimum is greater than maximum in this random range.
  • line 15: Minimum is greater than maximum in this random range.
  • line 16: Minimum is greater than maximum in this random range.
  • line 18: Minimum is greater than maximum in this random range.
  • line 20: Minimum is greater than maximum in this random range.
  • line 21: Minimum is greater than maximum in this random range.

Configure ​

In custos.json:

json
{
  "rules": {
    "IncorrectRandomRange": {
      "enabled": false
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore IncorrectRandomRange

/**
 * @noinspection IncorrectRandomRangeInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.