Current Location: Home> Latest Articles> Detailed Guide to PHP's range() Function: How to Create Arrays and Set Increment Steps

Detailed Guide to PHP's range() Function: How to Create Arrays and Set Increment Steps

M66 2025-06-12

Introduction to the range() Function

The range() function in PHP is used to create an array containing elements within a specified range. With it, you can easily generate a sequence of numbers arranged by a specific step (increment). This function is particularly useful when you need to generate a series of consecutive numbers.

Syntax

range(start, end, step)

Parameters

  • start - The starting value of the sequence.
  • end - The ending value of the sequence.
  • step - The increment between values in the sequence. The default value is 1. You can specify this parameter to control the step size of the sequence.

Return Value

The range() function returns an array containing all elements from the start value to the end value. If a step parameter is provided, the array elements will be incremented by the specified step.

Example

Here’s a simple example showing how to use the range() function to generate a sequence from 0 to 12, with a step of 3:

<?php

$number = range(0,12,3);

print_r ($number);

?>

Output

The output of running the above code will be as follows:

Array

(

[0] => 0

[1] => 3

[2] => 6

[3] => 9

[4] => 12

)

Conclusion

The range() function is a very useful tool in PHP that allows you to quickly generate an array of numbers within a specified range. You can customize the starting value, ending value, and step to suit your specific needs. We hope that this article and its example help you better understand how to use the range() function effectively.