PHP Faker and optional()

I hit something today that the documentation did not state properly. If you are using the popular Faker library, which is a great library, then is a good chance you tried to use the optional() function.

Basically, optional takes a decimal value to generate a NULL or valid value for the provider that you use. The documentation states you can pass 0 to 1 but this isn’t true:

// optional() accepts a weight argument to specify the probability of receiving the default value.
// 0 will always return the default value; 1 will always return the provider. Default weight is 0.5 (50% chance).
$faker->optional($weight = 0.1)->randomDigit; // 90% chance of NULL
$faker->optional($weight = 0.9)->randomDigit; // 10% chance of NULL

In fact, if you load up to code for vendor/fzaninotto/faker/src/Faker/Provider/Base.php, you can see that there is a TODO that states this part must be removed in v2 and the code is:

if ($weight > 0 && $weight < 1 && mt_rand() / mt_getrandmax() <= $weight) {
     return $this->generator;
}

Problem is, if you pass 1 as the weight, it skips that part and takes the 1 to be 1% because the next case is 0 to 100…

I’ll open a bug report to fix the documentation but until then, take it for granted that you should multiply 1 by 100 if you wanted to pass a weight of 1.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.