• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

WP Bitz

A curated collection of code snippets for WordPress

  • Home
  • About
  • Blog
  • Code Snippets
You are here: Home / Code Snippets / Random Number Generator

Random Number Generator

September 4, 2020

This post brought to you by RocketGeek, ButlerBlog, and the following:

 

/**
 * Generates a random number of a fixed number of digits.
 * 
 * The use of STR_PAD_LEFT allows the result to ALWAYS be the given number of
 * digits, using leading zeros in instances where the number is less than the
 * number of digits (such as 000001 or 002345 ).
 */

// The number of digits.
$x = 6;

// Generate a random $x digit number.
$number = str_pad( rand( 0, pow( 10, $x )-1 ), $x, '0', STR_PAD_LEFT );

Chad Butler

Primary Sidebar

Join for free!

Get free code snippets, WordPress best practices, and practical Content Marketing advice from seasoned WordPress expert Chad Butler (butlerblog):

Recent Posts

  • Add a Database Connection to use WPDB
  • Notice: Function WP_Block_Patterns_Registry::register was called incorrectly
  • Use WP-CLI to back up your site
  • Bitnami WordPress Autoptimize cannot write to the cache directory
  • Create and delete WordPress sites in XAMPP with a batch file

Copyright © 2025 · Maker Pro on Genesis Framework · WordPress · Log in