RandomStuff
in package
Random data generation utility with secure fallback mechanisms
Provides comprehensive random data generation capabilities for testing, development, and simulation purposes. Uses secure random number generation (random_int) with automatic fallback to mt_rand when cryptographically secure randomness fails.
Core Features
- Words & Identifiers: Human-readable identifiers using curated word lists
- Strings & Data: Customizable random strings, passwords, hex values
- Numbers & Ranges: Integers, floats with precise range control
- Collections: Array shuffling, sampling, weighted selection
- Personal Data: Names, emails, addresses for testing scenarios
- Specialized Formats: Credit cards, API keys, IP addresses, coordinates
- Gaming & Fun: Dice rolling, playing cards, Lorem Ipsum text
Security Model
All methods attempt secure random generation first, with graceful fallback:
- Primary: Uses random_int() for cryptographically secure randomness
- Fallback: Uses mt_rand() if Random\RandomException occurs
- Never fails: All methods complete successfully regardless of random source
Word List Caching
Implements lazy-loaded caching for word lists to optimize performance when generating multiple word-based identifiers. Cache persists for script duration.
Usage Patterns
Static factory pattern - all methods are static and can be called directly without instantiation. Designed for utility usage across application layers.
Tags
Table of Contents
Properties
- $cachedWordList : array<string|int, string>|null
- Cached word list for performance optimization during multiple word generation calls
Methods
- apiKey() : string
- Generate a random API key using alphanumeric characters
- bool() : bool
- Generate a random boolean value with optional probability weighting
- cachedWordList() : array<string|int, string>
- Get the cached word list, loading it on first access
- coordinates() : array{latitude: float, longitude: float}
- Generate random geographic coordinates within specified bounds
- creditCard() : string
- Generate a random credit card number for testing purposes
- date() : string
- Generate a random date within a specified range
- dice() : array<string|int, int>
- Simulate rolling dice with customizable sides and quantity
- email() : string
- Generate a random email address for testing purposes
- firstName() : string
- Generate a random first name with optional gender specification
- float() : float
- Generate a random float within a specified range with precision control
- fullName() : string
- Generate a random complete name with optional gender specification
- getElement() : string|null
- Return a random element from the provided array
- hex() : string
- Generate a random hexadecimal string of specified length
- int() : int
- Generate a random integer within a specified range (inclusive)
- ip() : string
- Generate a random IP address in IPv4 or IPv6 format
- lastName() : string
- Generate a random surname from curated list
- lorem() : string
- Generate Lorem Ipsum text with specified word count
- macAddress() : string
- Generate a random MAC address in standard colon-separated format
- myThreeWords() : string
- Generate a stable, human-friendly identifier for the current request
- password() : string
- Generate a random password with customizable character set requirements
- phoneNumber() : string
- Generate a random US phone number in standard format
- playingCard() : string
- Draw a random playing card from a standard 52-card deck
- resetCache() : void
- Reset the cached word list for testing purposes
- sample() : array<string|int, mixed>
- Select random elements from an array without replacement
- shuffle() : array<string|int, mixed>
- Shuffle an array using Fisher-Yates algorithm with secure randomness
- state() : string
- Generate a random US state name or abbreviation
- string() : string
- Generate a random string of specified length using a custom character set
- time() : string
- Generate a random time of day in specified format
- timezone() : string
- Generate a random timezone identifier from PHP's supported list
- urlSafe() : string
- Generate a URL-safe random string suitable for web applications
- weighted() : string|int|null
- Weighted random selection from an associative array
- words() : string
- Generate a string of random words joined by a specified separator
- zipCode() : string
- Generate a random US ZIP code in 5-digit format
Properties
$cachedWordList
Cached word list for performance optimization during multiple word generation calls
private
static array<string|int, string>|null
$cachedWordList
= null
Stores the result of Lists::bigFiveCharWords() after first access to avoid repeated expensive list generation. Cache persists for the entire script execution duration and is shared across all word generation methods.
Array of five-character words, or null if not yet loaded
Tags
Methods
apiKey()
Generate a random API key using alphanumeric characters
public
static apiKey([int $length = 32 ]) : string
Creates random strings suitable for API key simulation, token generation, or identifier creation in development environments. Uses only alphanumeric characters for broad compatibility across systems and protocols.
Character Set
- Letters: a-z, A-Z (case-sensitive)
- Numbers: 0-9
- No special characters or symbols
- Safe for URL transmission and database storage
Use Cases
- API key simulation for testing
- Development environment tokens
- Database record identifiers
- Configuration placeholders
Parameters
- $length : int = 32
-
Length of the API key (default: 32)
Tags
Return values
string —Random alphanumeric API key
bool()
Generate a random boolean value with optional probability weighting
public
static bool([float $probability = 0.5 ]) : bool
Returns true or false randomly, with optional probability control for biasing results toward true values. Uses integer-based random generation for consistent behavior across random sources.
Probability Control
- Default: 50% chance of true (unbiased)
- Custom: Specify probability as decimal (0.0 to 1.0)
- Examples: 0.7 = 70% chance of true, 0.1 = 10% chance of true
- Edge cases: 0.0 = always false, 1.0 = always true
Parameters
- $probability : float = 0.5
-
Probability of returning true (0.0-1.0, default: 0.5)
Tags
Return values
bool —Random boolean value
cachedWordList()
Get the cached word list, loading it on first access
public
static cachedWordList() : array<string|int, string>
Implements lazy loading for the five-character word list used by word generation methods. Caches the list in static variable for performance optimization during multiple word generation calls within same request.
Caching Strategy
- Lazy loading: Only loads when first accessed
- Static storage: Persists for entire script execution
- Performance: Avoids repeated expensive list generation
- Memory: Single copy shared across all word generation methods
Cache Behavior
- First call: Loads from Lists::bigFiveCharWords() and caches
- Subsequent calls: Returns cached array without reloading
- Testing: Use resetCache() to clear for testing scenarios
Tags
Return values
array<string|int, string> —Array of five-character English words
coordinates()
Generate random geographic coordinates within specified bounds
public
static coordinates([array<string, float> $bounds = [] ]) : array{latitude: float, longitude: float}
Creates random latitude and longitude pairs for geographic testing scenarios. Supports custom boundary specification for regional testing or uses global bounds as default. Returns coordinates with appropriate decimal precision.
Coordinate Ranges
- Latitude: -90 to 90 degrees (South to North)
- Longitude: -180 to 180 degrees (West to East)
- Default: Global coverage (entire Earth)
- Custom: Specify regional boundaries via bounds array
Boundary Specification
Optional bounds array accepts keys:
- 'min_lat': Minimum latitude
- 'max_lat': Maximum latitude
- 'min_lng': Minimum longitude
- 'max_lng': Maximum longitude
Output Format
Returns associative array with 'latitude' and 'longitude' keys, each containing floating-point values with 6 decimal places precision.
Parameters
- $bounds : array<string, float> = []
-
Optional boundary constraints
Tags
Return values
array{latitude: float, longitude: float} —Random coordinate pair
creditCard()
Generate a random credit card number for testing purposes
public
static creditCard([string $type = 'visa' ]) : string
Creates realistic-looking credit card numbers that follow proper formatting patterns for major card types. Numbers are for testing only and are not valid for actual transactions or financial processing.
Supported Card Types
- 'visa': 4###-####-####-#### format
- 'mastercard': 5###-####-####-#### format
- 'amex': 3###-######-##### format (American Express)
- Default: Uses Visa format for unrecognized types
Testing Safety
- Numbers are randomly generated, not from valid ranges
- Do not pass Luhn algorithm validation
- Safe for form testing without financial risk
- Should never be used for actual payment processing
Parameters
- $type : string = 'visa'
-
Card type: 'visa', 'mastercard', or 'amex' (default: 'visa')
Tags
Return values
string —Formatted credit card number for testing
date()
Generate a random date within a specified range
public
static date([DateTimeInterface|string $start = '-1 year' ][, DateTimeInterface|string $end = 'now' ][, string $format = 'Y-m-d' ]) : string
Creates random DateTimeImmutable objects between two boundary dates. Accepts various input formats and provides consistent date range generation for testing temporal data scenarios.
Input Format Flexibility
- DateTimeInterface objects (DateTime, DateTimeImmutable)
- String dates in any format parseable by DateTime constructor
- Relative formats: "now", "+1 week", "2023-01-01", etc.
- Default range: January 1, 2020 to current date/time
Output Consistency
- Always returns DateTimeImmutable for immutability
- Preserves timezone information from input dates
- Random time component included (not just date)
Parameters
- $start : DateTimeInterface|string = '-1 year'
-
Start date (default: "2020-01-01")
- $end : DateTimeInterface|string = 'now'
-
End date (default: "now")
- $format : string = 'Y-m-d'
Tags
Return values
string —Random date within specified range
dice()
Simulate rolling dice with customizable sides and quantity
public
static dice([int $sides = 6 ][, int $count = 1 ]) : array<string|int, int>
Simulates physical dice rolling for gaming applications, probability testing, or random number generation scenarios requiring discrete uniform distribution. Supports various die types and multiple dice rolls simultaneously.
Dice Configuration
- Sides: Number of faces per die (default: 6 for standard cube)
- Count: Number of dice to roll simultaneously (default: 1)
- Range: Each die result from 1 to sides (inclusive)
- Common types: d4(4), d6(6), d8(8), d10(10), d12(12), d20(20)
Return Format
Returns array of individual die results, not summed total. Preserves each die's result for game mechanics requiring individual values.
Parameters
- $sides : int = 6
-
Number of faces per die (default: 6)
- $count : int = 1
-
Number of dice to roll (default: 1)
Tags
Return values
array<string|int, int> —Individual results from each die roll
email()
Generate a random email address for testing purposes
public
static email([string $domain = '' ]) : string
Creates realistic-looking email addresses using random word combinations for usernames and either specified or randomly selected domains. Designed specifically for development and testing scenarios.
Username Generation
- Uses two random words separated by dot
- Example: "brave.eagle", "ocean.storm", "red.mountain"
- Words sourced from cached word list for consistency
Domain Handling
- Custom domain: Use provided domain parameter
- Random domain: Selects from predefined test domains
- Test domains: example.com, test.org, demo.net, sample.io
- All domains are non-functional for safety
Parameters
- $domain : string = ''
-
Custom domain to use (optional, uses random if empty)
Tags
Return values
string —Random email address suitable for testing
firstName()
Generate a random first name with optional gender specification
public
static firstName([string $gender = 'any' ]) : string
Returns random first names from curated lists based on gender preference. Supports male, female, unisex, and combined name pools for diverse testing scenarios and demographic simulation.
Name Categories
- Male: Traditional masculine names
- Female: Traditional feminine names
- Unisex: Names commonly used for any gender
- Any: Combined pool of all three categories
Gender Selection Logic
- 'male': Returns only from male name list
- 'female': Returns only from female name list
- 'unisex': Returns only from unisex name list
- 'any' or other: Returns from combined male+female+unisex lists
Parameters
- $gender : string = 'any'
-
Gender preference: 'male', 'female', 'unisex', or 'any' (default: 'any')
Tags
Return values
string —Random first name matching gender criteria
float()
Generate a random float within a specified range with precision control
public
static float([float $min = 0.0 ][, float $max = 1.0 ][, int $precision = 2 ]) : float
Creates random floating-point numbers within defined bounds with customizable decimal precision. Uses integer-based random generation internally for consistency across different random sources.
Precision Implementation
- Uses integer multiplication internally for consistent results
- Rounds to specified decimal places using round()
- Default precision: 2 decimal places
- Maximum precision limited by PHP float precision
Range Handling
- Both bounds are achievable (inclusive behavior)
- Supports negative numbers and zero
- Min and max can be equal for fixed-value testing
Parameters
- $min : float = 0.0
-
Minimum value (inclusive, default: 0.0)
- $max : float = 1.0
-
Maximum value (inclusive, default: 1.0)
- $precision : int = 2
-
Number of decimal places (default: 2)
Tags
Return values
float —Random float within specified range and precision
fullName()
Generate a random complete name with optional gender specification
public
static fullName([string $gender = 'any' ]) : string
Combines random first and last name generation to create realistic full names for testing user accounts, contact databases, or form validation scenarios. Leverages existing first name gender logic while using universal surname list.
Name Construction
- First name: Selected based on gender parameter
- Last name: Random selection from surname database
- Format: "FirstName LastName" with single space separator
- No middle names or suffixes included
Parameters
- $gender : string = 'any'
-
Gender preference for first name: 'male', 'female', 'unisex', or 'any' (default: 'any')
Tags
Return values
string —Random complete name in "First Last" format
getElement()
Return a random element from the provided array
public
static getElement(array<string|int, string> $strings) : string|null
Selects a random element from an array using PHP's array_rand function. Returns null for empty arrays to prevent errors and provide predictable behavior for edge cases.
Array Handling
- Preserves original array keys and values
- Works with both indexed and associative arrays
- Returns actual array values, not keys
- Safe for arrays containing mixed data types
Parameters
- $strings : array<string|int, string>
-
Array of strings to choose from
Tags
Return values
string|null —A random element, or null if the array is empty
hex()
Generate a random hexadecimal string of specified length
public
static hex([int $length = 32 ]) : string
Creates random hexadecimal strings using lowercase letters (a-f) and digits (0-9). Commonly used for generating hash-like identifiers, tokens, or color values.
Output Format
- Characters: 0-9, a-f (lowercase only)
- No prefix (no "0x" or "#")
- Fixed length as specified
- Suitable for hash simulation or color generation
Parameters
- $length : int = 32
-
Length of the hex string (default: 32)
Tags
Return values
string —Random hexadecimal string using 0-9a-f
int()
Generate a random integer within a specified range (inclusive)
public
static int([int $min = 0 ][, int $max = 100 ]) : int
Produces random integers within defined bounds using secure random generation with automatic fallback. Both minimum and maximum values are inclusive in the possible results.
Range Behavior
- Both min and max values are included in possible results
- Works with negative numbers and zero
- Handles ranges of any size (min can equal max)
- Default range: 0 to 100 inclusive
Security Fallback
Uses random_int() primarily, falls back to mt_rand() if needed. Both functions handle the inclusive range correctly.
Parameters
- $min : int = 0
-
Minimum value (inclusive, default: 0)
- $max : int = 100
-
Maximum value (inclusive, default: 100)
Tags
Return values
int —Random integer within specified range
ip()
Generate a random IP address in IPv4 or IPv6 format
public
static ip([string $type = 'ipv4' ]) : string
Creates random IP addresses for testing network applications, configuration validation, or simulation scenarios. Supports both IPv4 and IPv6 formats with appropriate range restrictions for realistic addresses.
IPv4 Generation
- Format: xxx.xxx.xxx.xxx
- First octet: 1-254 (avoids 0 and 255)
- Middle octets: 0-255 (full range)
- Last octet: 1-254 (avoids 0 and 255)
- Excludes common reserved ranges for realistic simulation
IPv6 Generation
- Format: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
- Each segment: 4-character hexadecimal (0000-ffff)
- Full 128-bit address space representation
- Uses lowercase hex characters for consistency
Parameters
- $type : string = 'ipv4'
-
IP version type: 'ipv4' or 'ipv6' (default: 'ipv4')
Tags
Return values
string —Random IP address in specified format
lastName()
Generate a random surname from curated list
public
static lastName() : string
Returns random last names from a comprehensive surname database suitable for testing user profiles, contact lists, or demographic simulations. Names are culturally diverse and commonly used in English-speaking regions.
Tags
Return values
string —Random surname/last name
lorem()
Generate Lorem Ipsum text with specified word count
public
static lorem([int $words = 10 ]) : string
Creates pseudo-Latin placeholder text for layout testing, content simulation, and design mockups. Uses traditional Lorem Ipsum word pool with randomized selection and proper sentence formatting.
Text Formatting
- First word capitalized for sentence appearance
- All words separated by single spaces
- Ends with period for proper sentence structure
- No paragraph breaks or additional punctuation
Word Selection
- Random selection from classical Lorem Ipsum vocabulary
- Words may repeat naturally based on random selection
- Maintains Lorem Ipsum's pseudo-Latin appearance
Parameters
- $words : int = 10
-
Number of words to generate (default: 10)
Tags
Return values
string —Lorem Ipsum text formatted as single sentence
macAddress()
Generate a random MAC address in standard colon-separated format
public
static macAddress() : string
Creates random Media Access Control (MAC) addresses for network testing, device simulation, or configuration scenarios. Uses standard IEEE 802 formatting with lowercase hexadecimal notation.
MAC Address Format
- Pattern: xx:xx:xx:xx:xx:xx
- Each segment: Two lowercase hexadecimal digits
- Separators: Colons between each byte pair
- Example: "a1:b2:c3:d4:e5:f6"
Address Space
- Full 48-bit address space (6 bytes)
- Each byte: 0x00 to 0xFF (0-255 decimal)
- No vendor-specific prefix enforcement
- Purely random generation for testing purposes
Tags
Return values
string —Random MAC address in colon-separated hex format
myThreeWords()
Generate a stable, human-friendly identifier for the current request
public
static myThreeWords() : string
Creates and caches a unique identifier composed of three random English words, each exactly five characters long. The result remains constant for the duration of the script execution and is useful for log tagging, request correlation, or simplified debugging without relying on UUIDs.
Caching Behavior
- Generated once per script execution
- Subsequent calls return the same cached value
- Uses static variable for persistence
- Independent of the main word list cache
Use Cases
- Request tracking in logs
- Session identification in debugging
- Human-readable correlation IDs
- Simplified request monitoring
Tags
Return values
string —A unique, three-word identifier using 5-character words
password()
Generate a random password with customizable character set requirements
public
static password([int $length = 12 ][, bool $includeSymbols = true ][, bool $includeNumbers = true ][, bool $includeUppercase = true ][, bool $includeLowercase = true ]) : string
Creates secure passwords by combining different character types based on specified criteria. Ensures at least one character from each enabled type appears in the final password for security compliance.
Character Type Control
- Lowercase letters: a-z (includeLowercase)
- Uppercase letters: A-Z (includeUppercase)
- Numbers: 0-9 (includeNumbers)
- Symbols: !@#$%^&*()_+-=[]}|;:,.<>? (includeSymbols)
Security Guarantees
- At least one character from each enabled type
- Remaining positions filled randomly from combined character set
- Uses secure random generation with fallback
- No predictable patterns in character placement
Parameter Validation
Throws InvalidArgumentException if all character types are disabled, preventing generation of empty passwords.
Parameters
- $length : int = 12
-
Password length (default: 12)
- $includeSymbols : bool = true
-
Include special characters (default: true)
- $includeNumbers : bool = true
-
Include numbers (default: true)
- $includeUppercase : bool = true
-
Include uppercase letters (default: true)
- $includeLowercase : bool = true
-
Include lowercase letters (default: true)
Tags
Return values
string —Random password meeting specified criteria
phoneNumber()
Generate a random US phone number in standard format
public
static phoneNumber() : string
Creates random phone numbers following the North American Numbering Plan (NANP) format. Uses realistic area codes and exchange codes while avoiding reserved or special-purpose number ranges.
Phone Number Format
- Pattern: (xxx) xxx-xxxx
- Area code: 200-999 (avoids 0xx and 1xx reserved ranges)
- Exchange: 200-999 (avoids 0xx and 1xx reserved ranges)
- Number: 1000-9999 (avoids service codes like x11)
NANP Compliance
- Follows North American Numbering Plan restrictions
- Avoids reserved and special-purpose ranges
- Generates realistic-looking test numbers
- Safe for form testing without contacting real numbers
Tags
Return values
string —Random US phone number in (xxx) xxx-xxxx format
playingCard()
Draw a random playing card from a standard 52-card deck
public
static playingCard() : string
Generates random playing cards using standard deck composition with four suits and thirteen ranks. Returns cards in traditional notation format suitable for card game simulation and testing.
Card Components
- Suits: Spade (♠), Heart (♥), Diamond (♦), Club (♣)
- Ranks: A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K
- Format: RankSuit (e.g., "A♠", "10♥", "K♦")
- Deck size: 52 cards (13 ranks × 4 suits)
Unicode Symbols
Uses Unicode suit symbols for authentic playing card representation. Compatible with most modern systems and display contexts.
Tags
Return values
string —Random playing card in "RankSuit" format
resetCache()
Reset the cached word list for testing purposes
public
static resetCache() : void
Clears the internal word list cache to force reload on next access. Primarily used in testing scenarios to ensure clean state between test runs or when testing cache behavior itself.
Testing Use Cases
- Unit test isolation: Clear cache between tests
- Memory testing: Verify cache loading behavior
- Performance testing: Measure cache vs non-cache performance
- State reset: Ensure predictable starting conditions
Production Impact
Safe to call in production but unnecessary since cache improves performance. Only clear cache if specific testing requirements demand it.
Tags
sample()
Select random elements from an array without replacement
public
static sample(array<string|int, mixed> $array[, int $count = 1 ][, bool $preserveKeys = false ]) : array<string|int, mixed>
Returns a random subset of array elements using shuffling-based sampling. Provides options for key preservation and handles edge cases gracefully by returning the entire array when sample size exceeds array size.
Sampling Behavior
- Without replacement: Each element appears at most once
- Random order in result unless preserveKeys is true
- Returns entire array if count >= array size
- Empty array returns empty array regardless of count
Key Handling Options
- preserveKeys=false: Returns indexed array [0,1,2...]
- preserveKeys=true: Maintains original array keys
- Default behavior removes original keys for cleaner usage
Parameters
- $array : array<string|int, mixed>
-
Array to sample from
- $count : int = 1
-
Number of elements to select (default: 1)
- $preserveKeys : bool = false
-
Whether to preserve original array keys (default: false)
Tags
Return values
array<string|int, mixed> —Random sample from input array
shuffle()
Shuffle an array using Fisher-Yates algorithm with secure randomness
public
static shuffle(array<string|int, mixed> $array) : array<string|int, mixed>
Implements the Fisher-Yates shuffle algorithm using secure random number generation to provide unbiased shuffling of array elements. Preserves original array keys and their associations with values.
Algorithm Implementation
- Fisher-Yates shuffle for unbiased randomization
- Preserves key-value associations during shuffle
- Works with both indexed and associative arrays
- Uses secure random_int() with mt_rand() fallback
Key Preservation
Unlike PHP's built-in shuffle(), this method maintains the relationship between keys and values while randomizing their order in the array.
Parameters
- $array : array<string|int, mixed>
-
Array to shuffle (any key/value types)
Tags
Return values
array<string|int, mixed> —Shuffled array with preserved key-value relationships
state()
Generate a random US state name or abbreviation
public
static state([bool $abbreviated = false ]) : string
Returns random US states from a comprehensive list including all 50 states plus common territories. Supports both full state names and standard two-letter postal abbreviations based on parameter selection.
Output Formats
- Full names: "California", "Texas", "New York"
- Abbreviations: "CA", "TX", "NY"
- Default: Returns full state names
- Abbreviation flag: Set true for postal codes
State Coverage
Includes all 50 US states plus common territories like DC, PR, etc. Uses official state names and USPS-approved abbreviations.
Parameters
- $abbreviated : bool = false
-
Return postal abbreviation instead of full name (default: false)
Tags
Return values
string —Random US state name or abbreviation
string()
Generate a random string of specified length using a custom character set
public
static string([int $length = 8 ][, string $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ]) : string
Core string generation method that creates random strings from any specified character set. Uses secure random generation with automatic fallback to mt_rand if cryptographically secure randomness fails.
Security Implementation
- Attempts random_int() for secure random index generation
- Falls back to mt_rand() if Random\RandomException occurs
- Continues generation seamlessly without user intervention
- Never throws exceptions for random generation failures
Character Set Flexibility
- Default: Full alphanumeric (letters + digits)
- Custom: Any string of characters for selection
- Supports Unicode characters in charset
- Characters can repeat in output based on selection probability
Parameters
- $length : int = 8
-
Length of the string to generate
- $charset : string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
-
Character set to use (default: alphanumeric)
Tags
Return values
string —Random string built from specified character set
time()
Generate a random time of day in specified format
public
static time([string $format = 'H:i:s' ]) : string
Creates random time values representing moments within a 24-hour day. Uses timestamp-based generation to ensure valid times and supports customizable formatting via PHP date format strings.
Time Generation
- Range: 00:00:00 to 23:59:59 (full 24-hour day)
- Method: Random timestamp selection within 86400 seconds
- Base: Uses gmdate() for consistent UTC time formatting
- Resolution: Second-level precision
Format Flexibility
Accepts any PHP date() format string for output customization:
- Default: "H:i:s" (24-hour format with seconds)
- 12-hour: "g:i:s A" for AM/PM format
- Custom: Any valid PHP date format pattern
Parameters
- $format : string = 'H:i:s'
-
PHP date format string (default: 'H:i:s')
Tags
Return values
string —Random time formatted according to specified pattern
timezone()
Generate a random timezone identifier from PHP's supported list
public
static timezone() : string
Returns random timezone identifiers from PHP's comprehensive timezone database. Useful for testing time-related functionality across different geographic regions and daylight saving time scenarios.
Timezone Format
- Standard: PHP DateTimeZone identifiers
- Examples: "America/New_York", "Europe/London", "Asia/Tokyo"
- Coverage: Global timezone database maintained by PHP
- Validity: All returned timezones are valid for DateTime operations
Use Cases
- Testing timezone-aware applications
- Simulating global user bases
- Validating time conversion logic
- Geographic distribution simulation
Tags
Return values
string —Random PHP timezone identifier
urlSafe()
Generate a URL-safe random string suitable for web applications
public
static urlSafe([int $length = 16 ]) : string
Creates random strings using only URL-safe characters: letters, numbers, hyphens, and underscores. Ideal for generating tokens, identifiers, or parameters that will be transmitted via URLs without encoding issues.
Character Set
Uses: a-z, A-Z, 0-9, hyphen (-), underscore (_)
- No special encoding required in URLs
- Safe for use in query parameters
- Compatible with most web standards
Parameters
- $length : int = 16
-
Length of the string (default: 16)
Tags
Return values
string —URL-safe random string
weighted()
Weighted random selection from an associative array
public
static weighted(array<string, numeric-string|int|float> $weights) : string|int|null
Selects a random key from the input array based on associated numeric weights. Higher weight values increase selection probability proportionally. Handles edge cases gracefully and provides predictable fallback behavior.
Weight Distribution
- Weights are relative, not absolute percentages
- Higher weights = higher probability of selection
- Example: [A=>70, B=>20, C=>10] gives A 70% chance, B 20%, C 10%
- Zero weights are valid and result in zero selection probability
Selection Algorithm
- Calculate total weight sum
- Generate random float from 0 to total weight
- Walk through weights until random value is reached
- Return associated key for selected weight range
Edge Case Handling
- Empty array: Returns null
- All zero weights: Returns last key as fallback
- Negative weights: Treated as zero (not recommended)
Parameters
- $weights : array<string, numeric-string|int|float>
-
Associative array of value => weight pairs
Tags
Return values
string|int|null —Selected key from weights array, or null if empty
words()
Generate a string of random words joined by a specified separator
public
static words([int $howManyWords = 3 ][, string $separator = '-' ][, array<string|int, string> $wordList = [] ]) : string
Creates human-readable identifiers by randomly selecting words from a word list and joining them with a separator. Uses secure randomness with graceful fallback to mt_rand if the secure random generator fails.
Word Source Hierarchy
- Custom word list if provided via $wordList parameter
- Cached internal word list (5-character English words)
- Falls back to mt_rand selection if random_int fails
Error Handling
If Random\RandomException occurs during secure random generation:
- Switches to mt_rand for remaining word selections
- Continues normal execution without throwing exceptions
- Ensures method always completes successfully
Parameters
- $howManyWords : int = 3
-
Number of words to include (default is 3)
- $separator : string = '-'
-
Separator used to join the words (default is '-')
- $wordList : array<string|int, string> = []
-
Optional custom word list to choose from
Tags
Return values
string —Concatenated string of randomly selected words
zipCode()
Generate a random US ZIP code in 5-digit format
public
static zipCode() : string
Creates random ZIP codes following the standard US postal format. Generates 5-digit codes within the valid range used by the United States Postal Service for testing address forms and location-based applications.
ZIP Code Format
- Length: Exactly 5 digits
- Range: 10000-99999 (avoids leading zeros)
- Format: #####
- No ZIP+4 extension included
Usage Context
Suitable for form testing, address validation, and location-based application development requiring realistic US postal codes.
Tags
Return values
string —Random 5-digit US ZIP code