Introduction

Array range is a useful PHP function that allows you to generate a range of elements in an array. It's a very powerful function that can save you a lot of time and effort when working with arrays.

Syntax

The syntax of the array range function is as follows:

array range ( mixed $start , mixed $end [, number $step = 1 ] )

Where:

  • $start: The first value of the sequence.
  • $end: The final value of the sequence.
  • $step: Optional. The increment between values. Default is 1.

Examples

Here are some examples to help you better understand how to use the array range function:

Example 1

Generate an array with values from 0 to 5:

<?php

$numbers = range(0, 5);
print_r($numbers);

Output:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)

Example 2

Generate an array with values from -5 to 5:

<?php

$numbers = range(-5, 5);
print_r($numbers);

Output:

Array
(
    [0] => -5
    [1] => -4
    [2] => -3
    [3] => -2
    [4] => -1
    [5] => 0
    [6] => 1
    [7] => 2
    [8] => 3
    [9] => 4
    [10] => 5
)

Example 3

Generate an array with even numbers from 0 to 10:

<?php

$numbers = range(0, 10, 2);
print_r($numbers);

Output:

Array
(
    [0] => 0
    [1] => 2
    [2] => 4
    [3] => 6
    [4] => 8
    [5] => 10
)

Advantages of using array range

Using array range has several advantages:

  • Saves time and effort: With array range, you can generate an array with a sequence of values in just one line of code.
  • Easy to use: The syntax of array range is straightforward and easy to understand.
  • Customizable: You can specify the start and end values, as well as the increment, allowing you to generate a wide range of sequences.

Conclusion

Array range is a very useful PHP function that can save you a lot of time and effort when working with arrays. It's easy to use, customizable, and can generate a wide range of sequences. We hope this guide has helped you better understand how to use the array range function in PHP.

Practice Your Knowledge

What does the range() function in PHP do?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?