Home >Backend Development >PHP Tutorial >Introduction to how to create a numeric array using the PHP range() function
In PHP, we often need to create arrays of numbers. At this time, PHP's range() function can come in handy. This article will introduce how to use the PHP range() function to create a numeric array.
The range() function creates an array containing numbers within a specified range. The basic syntax is as follows:
range($start, $end, $step)
Parameter explanation:
$start
: The number to start. If omitted, defaults to 0. $end
: The number to end. If omitted, defaults to 0. $step
: The interval between each number. If omitted, defaults to 1. Let’s look at a few examples.
$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 )
$numbers = range(0.1, 1.0, 0.1); print_r($numbers);
Output:
Array ( [0] => 0.1 [1] => 0.2 [2] => 0.3 [3] => 0.4 [4] => 0.5 [5] => 0.6 [6] => 0.7 [7] => 0.8 [8] => 0.9 [9] => 1 )
$numbers = range(10, 1, -1); print_r($numbers);
Output:
Array ( [0] => 10 [1] => 9 [2] => 8 [3] => 7 [4] => 6 [5] => 5 [6] => 4 [7] => 3 [8] => 2 [9] => 1 )
In addition to creating a numeric array, the range() function can also create an array of letters. For example, the following code can create an array of letters containing a~f:
$letters = range('a', 'f'); print_r($letters);
Output:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )
In addition to consecutive letters, the range() function can also specify a non-consecutive range of letters. For example, the following code can create an array of letters containing a, c, and e:
$letters = range('a', 'e', 2); print_r($letters);
Output:
Array ( [0] => a [1] => c [2] => e )
Finally, it should be noted that the parameters of the range() function can be variables . For example, the following code can create a number array based on the starting number and interval entered by the user:
$start = $_POST['start']; $step = $_POST['step']; $numbers = range($start, 100, $step); print_r($numbers);
In actual development, we can use the range() function to create a number array according to specific needs.
The above is the detailed content of Introduction to how to create a numeric array using the PHP range() function. For more information, please follow other related articles on the PHP Chinese website!