Cú pháp
The range() function creates an array containing a range of elements. It accepts a start value, an end value, and an optional step parameter.
range($start, $end, $step)
$start— the first value of the sequence.$end— the last value of the sequence.$step— optional; if set, it defines the increment between elements. Defaults to 1.
Ví dụ
The function works with both integers and characters. Below are common usage patterns.
Integer range without step
$numbers = range(1, 5);
// Result: [1, 2, 3, 4, 5]
Integer range with step
$numbers = range(0, 20, 5);
// Result: [0, 5, 10, 15, 20]
Character range
$letters = range('a', 'e');
// Result: ['a', 'b', 'c', 'd', 'e']
The range() function is useful for generating sequences quickly without writing explicit loops. It returns an indexed array whose elements span from $start to $end inclusive.
The range() function is one of those handy PHP tools that makes generating sequences of data effortless. Whether you need a list of numbers for looping logic or an array of letters for labeling items, this function handles both integers and characters with ease. The optional step parameter gives you fine control over the spacing between values, allowing you to skip elements or create custom intervals. Mastering built-in functions like range() is exactly the kind of practical knowledge that accelerates your PHP learning. Instead of writing tedious loops to build arrays manually, you can accomplish the same task in a single line of code. This efficiency frees you to focus on bigger challenges, like building database-driven applications or structuring reusable components. Small productivity gains like this add up quickly, helping you move from basics to expert-level projects without getting bogged down in repetitive code.
Learn PHP Tutorial