PHP range() Function Tutorial 🎯

beginner
25 min

PHP range() Function Tutorial 🎯

Welcome to our comprehensive guide on the range() function in PHP! This function is a powerful tool that generates an array with a specified range of numbers. Let's dive in and learn how to use it effectively.

Understanding the range() Function πŸ“

The range() function generates an array containing a specified range of numeric keys. It's a handy function when you need a sequence of numbers for various purposes, such as creating loops or manipulating data.

Syntax πŸ’‘

The syntax for the range() function in PHP is as follows:

php
array range ( int $start , int $end [, int $step = 1 ] )
  • $start: The starting number of the range.
  • $end: The ending number of the range (exclusive).
  • $step: The step value (increment/decrement) between each number in the range.

Practical Examples πŸ’»

Now, let's see some practical examples to help you grasp the concept better.

Example 1: Basic usage

php
<?php $numbers = range(1, 10); print_r($numbers); ?> Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )

In this example, we're generating an array with numbers from 1 to 10.

Example 2: Custom step value πŸ’‘

php
<?php $numbers = range(0, 20, 5); print_r($numbers); ?> Output: Array ( [0] => 0 [1] => 5 [2] => 10 [3] => 15 )

Here, we're generating an array with numbers from 0 to 20, but with a step value of 5.

Quiz Time πŸ“

Quick Quiz
Question 1 of 1

What does the `range()` function in PHP generate?

Stay tuned for more in-depth explanations on using the range() function effectively in your PHP projects! πŸš€