I'm trying to create a randomized string in PHP, and I get absolutely no output with this:
<?php function RandomString() { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randstring = ''; for ($i = 0; $i < 10; $i++) { $randstring = $characters[rand(0, strlen($characters))]; } return $randstring; } RandomString(); echo $randstring;
What am I doing wrong?
The rand() is an inbuilt function in PHP used to generate a random number ie., it can generate a random integer value in the range [min, max]. Syntax: rand(); The rand() function is used to generate a random integer.
The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.
php $check = array(); function generateNumber() { global $check; $page_no = mt_rand(1,20); $check[] = $page_no; if (count($check) != 1) { foreach ($check as $val) { if ($val == $page_no) { $page_no = mt_rand(1,10); continue; } } return $page_no; } else { return $page_no; } } ?>
To answer this question specifically, two problems:
$randstring
is not in scope when you echo it.Here's a code snippet with the corrections:
function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; }
Output the random string with the call below:
// Echo the random string. // Optionally, you can give it a desired string length. echo generateRandomString();
Please note that this generates predictable random strings. If you want to create secure tokens, see this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With