How to Generate Random String in PHP?
Hi Guys,
This article goes into detail on php generate random string. I explained simply step by step how to generate random string in php. I’m going to show you how to generate random alphanumeric string in php. In this article, we will implement a php generate random string fixed length. Follow the below tutorial step of random string generator PHP.
In PHP, you can generate a random string using various methods. One common way is to use the str_shuffle() function along with substr() to get a random portion of a shuffled character set. Here's a simple example:
index.php
<?php
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
/* Usage example: */
$randomString = generateRandomString(10);
echo $randomString;
?>
Output:
oBMzXTtOBU
This code will generate a random string of the specified length (default is 10 characters) using alphanumeric characters (both lowercase and uppercase letters) along with digits. You can adjust the length and character set according to your requirements.
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Add Facebook Share Button in PHP Website?
- PHP Format Number with 2 Decimals Example
- How to Get Time Difference in Hours and Minutes in PHP?
- How to Install PHP DOM Extension in Ubuntu 22.04?
- How to Install PHP Imagick Extension in Ubuntu 22.04?
- How to Extract Img SRC, Title and Alt from HTML in PHP?
- How to Install PHP 8.3 on Ubuntu 22.04?
- How to Install PHP 8.2 on Ubuntu 22.04?
- PHP array_merge() Function Example
- How to Get Last 5 Elements of Array in PHP?
- PHP Get First 2, 3, 4, 5, 10 Character from String Example
- How to Check Query Execution Time in PHP?
- Ubuntu PHP bz2 Extension Install Commands Example