Menü schliessen
Created: December 21st 2020
Last updated: December 21st 2020
Categories: IT Development
Author: Marcus Fleuti

Random number / chars generator

Tags:  character,  function,  id,  number,  PHP,  random,  unique
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

If you need to generate random numbers containing characters, i've create a PHP-Random-Number-Generator.

All you need to do is provide a string with the characters you want to use in the random number. To avoid redundances the function gets an ID from a .txt file and then (after the execution) adds 1 to the ID. So every random number is unique.

The function looks like that:

function generateVoucherNumber() {
    $n = 8;
    $voucher_code = '';
    $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for($i = 0;$i < $n;$i++) {
        $index = rand(0, strlen($chars) - 1);
        $voucher_code .= $chars[$index];
    }
    $old_id = (int)file_get_contents('/home/test/www/testproject/wp/wp-content/themes/septera-child/voucher/voucher_ids.txt');
    $new_id = $old_id + 1;

    file_put_contents('/home/test/www/testproject/wp/wp-content/themes/septera-child/voucher/voucher_ids.txt', $new_id);

    $id_with_chars = $voucher_code . $new_id;

    return $id_with_chars;
}