Generating random names with PHP.

This is a short tutorial on how to generate random names with PHP. This sort of thing can be useful for games and mock user accounts.

In this example, we have two PHP arrays. One contains a list of common forenames. The other contains a list of common surnames. Using the function mt_rand, we can generate a random full name:


//PHP array containing forenames.
$names = array(

//PHP array containing surnames.
$surnames = array(

//Generate a random forename.
$random_name = $names[mt_rand(0, sizeof($names) - 1)];

//Generate a random surname.
$random_surname = $surnames[mt_rand(0, sizeof($surnames) - 1)];

//Combine them together and print out the result.
echo $random_name . ' ' . $random_surname;

As you can see, it’s pretty straight forward. Note that we use mt_rand, simply because it’s “more random” than functions such as array_rand and rand. In the PHP snippet above, we basically grab a random element from each array before concatenating them and printing them out.

If you are looking for a scalable solution that involves more names (and names that are categorized by country and gender), then you should check out this list of common names, which is available in SQL & CSV format. Personally, I would avoid large PHP arrays containing forenames and surnames, simply because of memory concerns.