Question
PHP Random String Generator: Return Values, Scope, and Correct String Building
Question
I am trying to generate a random string in PHP, but this code produces no output:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
What is causing this, and how should the function be written so it correctly returns and displays a random 10-character string?
Short Answer
By the end of this page, you will understand why the original PHP code prints nothing, how function return values and variable scope work, and how to correctly build a random string one character at a time. You will also learn safer and more modern ways to generate random strings in PHP.
Concept
In PHP, a variable created inside a function belongs to that function unless its value is returned or otherwise passed out. This is called scope.
In the original code, $randstring is created inside RandomString(). After the function finishes, that local variable is not available outside the function. So this line does not work as expected:
echo $randstring;
That variable does not exist in the outer scope.
There is also a second issue: inside the loop, the code uses = instead of .=.
$randstring = $characters[rand(0, strlen($characters))];
This replaces the whole string on every loop iteration, so even if the function worked, it would only keep one final character instead of building a 10-character string.
A third issue is the random index range. strlen($characters) is one past the last valid index, because string positions start at 0. The last valid index is:
strlen() -
Mental Model
Think of a function like a small workshop.
- Inside the workshop, you create a product:
$randstring - When the work is done, you must hand the product out through the door using
return - If you do not capture that returned value outside, you still do not have it in your hands
Also think of building a string like stacking blocks:
=means throw away the old stack and replace it.=means add a new block to the existing stack
So if you want 10 characters, you must keep adding characters, not replacing the previous one each time.
Syntax and Examples
Correct basic version
<?php
function randomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring .= $characters[rand(0, strlen($characters) - 1)];
}
return $randstring;
}
$result = randomString();
echo $result;
Why this works
$randstringstarts as an empty string- The loop runs 10 times
- Each time, one random character is selected
.=appends that character to the stringreturnsends the finished string back$resultstores the returned value
Step by Step Execution
Consider this code:
<?php
function randomString($length = 5)
{
$characters = 'abc123';
$result = '';
for ($i = 0; $i < $length; $i++) {
$index = rand(0, strlen($characters) - 1);
$result .= $characters[$index];
}
return $result;
}
$value = randomString(5);
echo $value;
Step by step
- The function
randomString(5)is called. $charactersbecomes'abc123'.$resultstarts as .
Real World Use Cases
Random strings are used in many practical PHP applications:
- Temporary passwords
- Email verification codes
- Password reset tokens
- Unique filenames
- Invite codes
- Session-related identifiers
- Test data generation
Example: generating a simple order reference suffix
<?php
function randomString($length = 6)
{
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$result = '';
$max = strlen($chars) - 1;
for ($i = 0; $i < $length; $i++) {
$result .= $chars[random_int(0, $max)];
}
return $result;
}
$orderCode = 'ORD-' . randomString(6);
echo ;
Real Codebase Usage
In real projects, developers usually wrap this logic in a reusable function or utility class.
Common patterns include:
Parameterized length
Instead of hardcoding 10 characters, codebases often allow:
randomString(32)
Restricted character sets
For example, avoiding confusing characters like 0, O, l, and I:
$chars = '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ';
Guard clauses
Validate input early:
<?php
function randomString($length = 10)
{
if ($length < 1) {
return '';
}
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$result = ;
= () - ;
( = ; < ; ++) {
.= (, );
}
;
}
Common Mistakes
1. Echoing a local variable outside the function
Broken code:
<?php
function randomString()
{
$result = 'abc';
return $result;
}
randomString();
echo $result;
Why it fails:
$resultexists only inside the function- The returned value is ignored
Fix:
<?php
$value = randomString();
echo $value;
2. Replacing instead of appending
Broken code:
$result = $chars[rand(0, strlen($chars) - 1)];
This keeps only one character.
Fix:
Comparisons
| Concept | What it does | Good for | Notes |
|---|---|---|---|
= | Assigns or replaces a value | Setting initial value | Overwrites previous content |
.= | Appends to a string | Building strings in loops | Keeps previous content |
rand() | Generates a pseudo-random integer | Basic examples, simple scripts | Not best for security |
random_int() | Generates a stronger random integer | Tokens, codes, production use | Better choice in modern PHP |
echo randomString() | Prints returned value directly |
Cheat Sheet
Quick fix for the original problem
<?php
function randomString($length = 10)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $characters[rand(0, strlen($characters) - 1)];
}
return $result;
}
echo randomString();
Rules to remember
- Use
returnto send data out of a function - Store the returned value or echo it directly
- Variables inside a function are local
- Use
.=to build a string gradually - String indexes go from
0tostrlen($string) - 1
Safer random version
FAQ
Why does echo $randstring; print nothing in PHP?
Because $randstring was created inside the function, so it is not available outside that function. You need to capture the returned value.
Why does my function return only one character instead of 10?
Because you used = inside the loop, which replaces the string each time. Use .= to append characters.
Should I use rand() or random_int() in PHP?
Use random_int() when randomness matters, especially for tokens, codes, or security-related features. rand() is more basic.
How do I print a function's returned string in PHP?
Either store it first or print it directly:
$value = randomString();
echo $value;
or
echo randomString();
What is variable scope in PHP?
Scope defines where a variable can be accessed. A variable inside a function is local to that function unless returned or declared differently.
Mini Project
Description
Create a PHP function that generates invite codes for a small web application. Each code should be a random string made from letters and numbers. This project demonstrates function returns, local scope, string concatenation, loop-based string building, and optional function parameters.
Goal
Build a reusable PHP function that generates and prints random invite codes of different lengths.
Requirements
- Create a function that accepts the desired code length.
- Use a string of allowed characters containing uppercase letters, lowercase letters, and digits.
- Build the result one character at a time inside a loop.
- Return the finished string from the function.
- Print at least two generated codes with different lengths.
Keep learning
Related questions
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.
Convert a PHP Object to an Associative Array
Learn how to convert a PHP object to an associative array, including quick methods, recursion, pitfalls, and practical examples.
Convert a Postman Request to cURL and PHP cURL
Learn how to convert a Postman POST request into a cURL command and use the same request in PHP cURL with headers and body.