How can I create a true multi-byte string shuffle function in PHP?

Solution :

You can shuffle a multibyte string in PHP by splitting it into individual characters using mb_substr and mb_strlen, shuffling the array, then joining it back together:


<?php
$string = "Pretend I'm multibyte!";
$encoding = 'UTF-8';

// Get string length
$len = mb_strlen($string, $encoding);

// Split string into characters
$chars = [];
for ($i = 0; $i < $len; $i++) {
    $chars[] = mb_substr($string, $i, 1, $encoding);
}

// Shuffle the characters
shuffle($chars);

// Join back into a string
$shuffled = implode('', $chars);

echo $shuffled;
?>

Example Output:

rmedt tmu nIb’lyi!eteP

✅ Explanation

mb_strlen($string, $encoding) → get the number of characters in a multibyte-safe way.

mb_substr($string, $i, 1, $encoding) → extract one character at a time.

shuffle($chars) → randomizes the array of characters.

implode(”, $chars) → converts the shuffled array back into a string.

⚠️ Important: Always specify the encoding (UTF-8) when working with multibyte strings to avoid breaking characters.