7

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.

Koolstr
  • 464
  • 1
  • 10
  • 20
  • 4
    You could just shorten the returned zip code using [`substr()`](http://php.net/manual/en/function.substr.php) -> `$postcode = (strlen($faker->postcode) > 5) ? substr($faker->postcode,0,5) : $faker->postcode;` – Sean Dec 14 '15 at 00:00
  • 2
    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; http://sqlfiddle.com/#!9/814ba/1... Couldn't you just take the first 5 characters? – chris85 Dec 14 '15 at 00:00
  • 1
    "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. – ceejayoz Dec 22 '15 at 21:53

1 Answers1

6

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;.

mshaps
  • 884
  • 1
  • 6
  • 10