php fzaninotto Faker - How to Generate Only 5 Digit Zip Code?
Asked Answered
N

1

9

Is there a way to generate a 5 digit zip code/postcode using fzaninotto's Faker?

His provided function to do so, $faker->postcode, does not offer parameters to limit its size, so it often gives a 9-digit postcode instead of 5, e.g., 10278-4159 instead of 10278. This is problematic for seeding a database, because my sql database has a zipcode column of INT(5).

I know I can resort to just generating a random 5 digit number with Faker, but I wanted to know if there was a native way of generative 5 digit zip codes.

Neoteny answered 13/12, 2015 at 23:49 Comment(3)
You could just shorten the returned zip code using substr() -> $postcode = (strlen($faker->postcode) > 5) ? substr($faker->postcode,0,5) : $faker->postcode;Contractile
Zip codes shouldn't be integers. My city's zip code starts with a 0 so this would cause an issue. Demo of leading 0 issue; sqlfiddle.com/#!9/814ba/1... Couldn't you just take the first 5 characters?Determinate
"because my sql database has a zipcode column of INT(5)" Danger! Danger, Will Robinson! You're going to turn 02108 into 2108 and have to left-pad it for display. Zip codes are not integers.Sext
N
8

A workaround I found uses the postcode of the address class which always returns 5 digits.

Instead of $faker->postcode you can call Address::postcode().

Don't forget to include use Faker\Provider\Address;.

Nephogram answered 22/12, 2015 at 21:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.