Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Faker. How to create N unique words?

Tags:

php

faker

I need to create N unique words. It seems that 'words' doesn't work with 'unique'.

\Faker\Factory::create()->unique()->words(14);

...unique()->word() is working. I am trying to create 250 unique words like that:

for ($i = 1; $i <= 250; $i++) {
    $iadefaults[] = $faker->unique()->word();
}

but I get

Maximum retries of 10000 reached without finding a unique value

How can I create those 250 unique words with faker?

like image 626
John Smith Avatar asked Jan 31 '26 12:01

John Smith


1 Answers

Looks like I found a solution for your issue

Go to Faker's sources and there you'll find a Provider/Lorem.php file

At the very top of it there's a protected static $wordList propery that contains an array defining which words are returned by the generator. If you do count(array_count_values($wordList)); - you'll see a magic number of 182 unique words :) No wonder it was unable to get more unique values based on that list.

So you just need to put more unique words in that array and that will do the trick!

like image 114
Stas Parshin Avatar answered Feb 03 '26 01:02

Stas Parshin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!