How to generate random string in PHP

In this article, I will show you, how you can generate a random string in PHP. You can set the length of random string. Also, you can define all the possible characters you want in your random string.

In order to generate random string in PHP, we will first create a string of all the possible characters we want in our random string.

$str = "qwertyuiopasdfghjklzxcvbnm";

Then we are going to get the length of that string.

$str_length = strlen($str);

After that, we will create a variable that will hold the output value i.e. random string.

$output = "";

Loop through the number of characters you want in your random string.

$length = 6;

for ($a = 1; $a <= $length; $a++)
{
    // [section-1]
}

On the place of [section-1], we will get the random index from string of possible characters.

$random = rand(0, $str_length - 1);

And we will pick the random character from that string.

$ch = $str[$random];

Finally, we will append that character in our output string.

$output .= $ch;

If you echo $output; you will see a random string every time that code is executed. Here is the full code:

$str = "qwertyuiopasdfghjklzxcvbnm";
$str_length = strlen($str);
$output = "";
$length = 6;
for ($a = 1; $a <= $length; $a++)
{
    $random = rand(0, $str_length - 1);
    $ch = $str[$random];
    $output .= $ch;
}
echo $output;

Shuffle an array of objects – Javascript

To shuffle an array of objects or single values in Javascript, use the following function:

for (var a = 0; a < data.length; a++) {
	var x = data[a];
	var y = Math.floor(Math.random() * (a + 1));
	data[a] = data[y];
	data[y] = x;
}

First, we are looping through all array elements. data is our array of objects. First, we are saving the current array element in a separate variable named x. Then we are generating a random number. Math.random() will return a random number between 0.0 and 0.9. As our loop start from 0, so we are multiplying that random number by loop iteration number + 1. Since the number will be in floating points, so we can convert that into an integer by calling Math.floor() function. The floor function will round the number downwards and return it as an integer. That is now the index of the random element in the array.

Then we are replacing the current array element with this random array element. And finally, replace this random array element with the current element of loop.

This is the simplest way to shuffle an array of objects using vanilla Javascript. For more Javascript tutorials, please follow here.