RandoPHP, a PHP package for generating random values
By: Roberto Butti
Tags: Package, Open Source, PHP, Php Developers, Random

RandoPHP is a PHP open source package for generating random numbers, characters, strings and sequences. With this package you can:

Draw : Extract random items (sample) from an array. This is useful when you want to “draw” some numbers or items;

: Extract random items (sample) from an array. This is useful when you want to “draw” some numbers or items; Generate: useful for create random items like integer, byte, boolean, float, lat/long coordinates, char (numeric, alphabetic, alphanumeric), and sequences like array of integer or char.

With a fluent interface, you can control some behavior like:

minimum and maximum value;

how many items you want to create;

for sequences if you want or not duplicates (for example in the array [1,5,3,1,1], the value 1 is duplicated).

Why RandoPHP

I started to write RandoPHP in order to wrap up all methods, functions, approaches to generate values. Every time I needed some Random values in my applications, I see that I was writing the same piece of codes, applying the same controls and validations. Then, I decided to release it with an Open Source package.

Installation

You can install the package via composer:

composer require hi-folks/rando-php

Source code is available: https://github.com/Hi-Folks/rando-php

Usage

Once you installed the package, you can import the autoload file (if you are not using a framework that provides import all needed files) and them declare the right class via “use” statement, in your PHP file:

require __DIR__ . "/vendor/autoload.php";

use HiFolks\RandoPhp\Randomize;

Generate random stuff

Generate Char

Sometimes you want to obtain a random char, for example, a numeric char (‘0’..‘9’):

Randomize::char()->numeric()->generate();

Or you might want an alphabetic char (‘a’ ..‘z’ or ‘A’ ..‘Z’):

Randomize::char()->alpha()->generate();

You can generate both, alphabetic or numeric char (‘a’ ..‘z’ or ‘A’ ..‘Z’ or ‘0’..’9').

Randomize::char()->alphanumeric()->generate();

You can generate a lower case char (‘a’..’z’):

Randomize::char()->alpha()->lower()->generate();

You can generate an upper case char (‘A’..’Z’):

Randomize::char()->alpha()->upper()->generate();

You can generate a special character.

A special character is one of ‘!”#$%&’()*+,-./:;<=>?@[\]^_`{|}~’:

$specialChar = Randomize::char()->specialCharacters()->generate();

Generate Boolean

Sometimes you want to obtain a random boolean true or false (flip a coin, yes or no, red or blue pillow … ):

$randomBool = Randomize::boolean()->generate(); // true or false

Generate a Float

Sometimes you want to obtain a random float (default min — max range of 0.0–1.0). For example, you want to generate a random number in the range 0.0 to 1.0:

$randomFloat = Randomize::float()->generate();

Or you can set the range, for example 0.0 to 90.0, which is equivalent to ->min(0)->max(90):

$randomFloat = Randomize::float()->min(0)->max(90)->generate();

Generate an Integer

Sometimes you want to obtain a random integer.

$randomNumber = Randomize::integer()->generate();

By default you will obtain an integer between 0 .. 100.

If you want to customize the range ( min and max ) you have some methods like min(), max(), range() and a construct.

For example, you want to roll the dice, you can use min() and max() method:

$randomNumber = Randomize::integer()->min(1)->max(6)->generate();

The same thing using range() method, instead of min() and max():

$randomNumber = Randomize::integer()->range(1,6)->generate();

You can use a shortcut helper to generate an integer calling the constructor with min and max:

$randomNumber = Randomize::integer(1,6)->generate();

Generate bytes

Sometime you want to obtain some random bytes (hexadecimal). For example, you want to generate a random RGB color (a hex triplet in hexadecimal format):

$randomRGB = Randomize::byte()->length(3)->generate();

Generate a Date

Sometimes you want to obtain a random date. For example, you want to generate a random date:

$randomDate = Randomize::datetime()->generate();

By default, a date between the first day of current year to the last day of current year.

If you want to define the range, for example a range of 01 Jan 2020 to 10 Jan 2020, which is equivalent to ->min(‘2020–01–01’)->max(‘2020–01–10’):

$randomDate = Randomize::datetime()->min(‘2020–01–01’)->max(‘2020–01–10’)->generate();

You can even specify your preferred format for the random date generated, by using format() method:

$randomDate = Randomize::datetime()->format(‘d-M-Y’)->generate();

You can use min() and max() with format():

$randomDate = Randomize::datetime()->min(‘2020–01–01’)->max(‘2020–01–10’)->format(‘d-M-Y’)->generate();

With the latest example you can obtain something like: “05-Jan-2020”.

Generate sequences

Sometimes, you want to obtain some random sequences. For example, you want to roll the dice 15 times:

$randomRolls = Randomize::sequence()->min(1)->max(6)->count(15)->generate();

// [3,6,5,5,2,2,4,1,4,4,5,4,5,2,6]

Sometime you want to obtain some random char sequences. For example, char sequences of length 10:

$randomChars = Randomize::sequence()->chars()->count(10)->generate();

// ["b","q","f","k","o","o","m","i","z","h"]

Or you might want numeric char sequences.

$randomChars = Randomize::sequence()->chars()->numeric()->count(10)->generate();

// ["9","5","8","6","5","4","2","9","7","2"]

Or you might want alphabetical char sequences.

$randomChars = Randomize::sequence()->chars()->alpha()->count(10)->generate();

// ["t","f","U","O","r","Y","C","S","g","J"]

Yes, even both.

$randomChars = Randomize::sequence()->chars()->alphanumeric()->count(10)->generate();

// ["L","5","h","A","c","q","C","W","F","z"]

You want 20 lowercase letters as string, you could use asString() method:

$randomString = Randomize::sequence()->chars()->alphaLowerCase()->count(20)->asString()->generate();

// "ybmzekmvvqpzviswdhob"

You want a string with 20 upper case letters:

$randomString = Randomize::sequence()->chars()->alphaUpperCase()->count(20)->asString()->generate();

// "LIYSENBIJRSBWVMEFEVA"

Sometimes you want to get some random numbers array without duplicates. For example, you want to play “Tombola” (extracting number from 1 to 90 without duplicates):

$randomTombola = Randomize::sequence()->min(1)->max(90)->count(90)->noDuplicates()->generate();

Sometime you want to obtain some random letters array without duplicates.

$randomChars = Randomize::sequence()->chars()->count(10)->noDuplicates()->generate();

// ["e","j","b","s","o","z","x","i","c","l"]

Or you might want numeric char array without duplicates. For example, char sequences of length 10:

$randomChars = Randomize::sequence()->chars()->numeric()->count(10)->noDuplicates()->generate();

// ["6","0","8","9","4","3","5","7","2","1"]

Or you might want letters array without duplicates.

$randomChars = Randomize::sequence()->chars()->alpha()->count(10)->noDuplicates()->generate();

If you want alphanumeric (letters and number) array without duplicates.

$randomChars = Randomize::sequence()->chars()->alphanumeric()->count(10)->noDuplicates()->generate();

Random String

If you want to generate random string (alphanumeric, only letters, only numbers, with no duplication, lower case, upper case etc) you can use Random Chars generation.

To generate a string use Randomize::chars():

$string = Randomize::chars()->generate();

Default behavior is:

10 chars;

only letters (a-z);

lower case;

duplication is allowed (the string ‘aba’ has a duplication for ‘a’ char).

You can change the default values with some methods and parameters.

Methods availabe, to set the type of chars (numeric, alpha, alphanumeric…):

alpha(): for selecting ‘a-z’, ‘A-Z’;

alphanumeric(): for selecting ‘a-z’, ‘A-Z’, ‘0–9’;

numeric(): for selecting ‘0–9’;

alphaLowerCase(): for selecting ‘a-z’;

alphaUpperCase(): for selecting ‘A-Z’;

specialCharacters(): for selecting !”#$%&’()*+,-./:;<=>?@[\]^_`{|}~

You have also some methods to “control” the output, for example avoid duplications:

unique() : it generates a string with at most one occurrence per character.

For example, if you want to generate a string with 16 numeric chars (‘0’-’9'):

$string = Randomize::chars(16)->numeric()->generate();

// "1607986939661884"

You could obtain something like this “1607986939661884”.

If you want to obtain a string with 20 chars, lower case and just letters (‘a’-’z’), and you want to avoid character duplications, you should use alphaLowerCase() and unique() methods:

$string = Randomize::chars(20)->alphaLowerCase()->unique()->generate();

// "tibuxmhwndjprzlagsqc"

You could obtain something like this: ‘tibuxmhwndjprzlagsqc’.

If you want to obtain a string with 20 chars, with letters and special characters, you should use specialCharacters() and alpha() methods:

$string = Randomize::chars(20)->specialCharacters()->alpha()->generate();

// "NZ`,{of)<-CeusEX+U<n"

You could obtain something like this: “NZ`,{of)<-CeusEX+U<n”.

Draw random stuff

If you have a list of values and you want to extract/select/draw one or more elements, you could use Draw class instead of Randomize.

For using Draw class you need to declare HiFolks\RandoPhp\Draw:

use HiFolks\RandoPhp\Draw;

For example if you have an array with some programming language and you want to pick one:

use HiFolks\RandoPhp\Draw; $randomLanguage = Draw::sample([“PHP”, “Python”, “Golang”, “Javascript”])->snap();

// "PHP"

With snap() method you obtain one element of the array.

If you want to obtain an array as result, you could use extract() method instead of snap():

$array=[“React.js”, “Vue.js”, “Svelte.js”, “Angular.js”, “Alpine.js”, “Vanilla js”]; $randomJs = Draw::sample($array)->extract();

Extract three JS frameworks that you could use in your next project:

$array=[“React.js”, “Vue.js”, “Svelte.js”, “Angular.js” , “Alpine.js”, “Vanilla js”];

$randomJs = Draw::sample($array)->count(3)->extract();

Extract three JS framework (duplicates allowed):

$array = [“React.js”, “Vue.js”, “Svelte.js”, “Angular.js”, “Alpine.js”, “Vanilla js”]; $randomJs = Draw::sample($array)->count(3)->allowDuplicates()->extract();

Warning

Under the hood RandoPHP uses some native PHP functions like:

- array_rand(): [PHP Doc for array_rand](https://www.php.net/manual/en/function.array-rand.php);

- random_int(): [PHP Doc for random_int](https://www.php.net/manual/en/function.random-int.php);

- shuffle(): [PHP Doc for shuffle](https://www.php.net/manual/en/function.shuffle);

- random_bytes(): [PHP Doc for random_bytes](https://www.php.net/manual/en/function.random-bytes).

These PHP functions use a pseudo random number generator that is not suitable for cryptographic purposes.

Some notes

To submit ideas or feature requests or issues, please take a look if your request is already there https://github.com/Hi-Folks/rando-php/issues.

If it is not present, you can create a new one https://github.com/Hi-Folks/rando-php/issues/new

The PHP versions supported are: ‘8.0’,’7.4',’7.3'.

All these versions are used in the CI/CD workflow . If you want to take a look about the workflow used , go to https://github.com/Hi-Folks/rando-php/blob/master/.github/workflows/php.yml

RandoPHP is released with the Open Source license: “the MIT License (MIT)”.