Bytes shuffling with PHP and the randomizer class

Published on 2023-09-10 • Modified on 2023-09-10

This snippet shows how to shuffle bytes with PHP and the randomizer class. We use the shufflebytes() function. This function does not correctly work if it contains unicode characters like emojis.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet271Trait
{
    public function snippet271(): void
    {
        $r = new \Random\Randomizer();
        $bytes = 'abcdefghijklmnopqrstuvwxyz';

        var_dump($bytes);
        echo PHP_EOL;
        var_dump($r->shuffleBytes($bytes));

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!