range() Function
range()函数是PHP中的一个内建函数,用于创建任意类型的元素数组,例如整数,在给定范围(从低到高)i内的字母。e, list的第一个元素被认为是low,最后一个元素被认为是high。
语法
1 | array range(low, high, step) |
参数:该函数接受以下三个参数:
- low:它将是range()函数生成的数组中的第一个值。
- high:它将是range()函数生成的数组中的最后一个值。
- step:当在范围中使用的递增值为1时使用。
返回值:它从低到高返回一个元素数组。
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Input : range(0, 6) Output : 0, 1, 2, 3, 4, 5, 6 Explanation: Here range() function print 0 to 6 because the parameter of range function is 0 as low and 6 as high. As the parameter step is not passed, values in the array are incremented by 1. Input : range(0, 100, 10) Output : 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 Explanation: Here range() function accepts parameters as 0, 100, 10 which are values of low, high, step respectively so it returns an array with elements starting from 0 to 100 incremented by 10. |
下面的程序演示了PHP中的range()函数:
例子1
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php // creating array with elements from 0 to 6 // using range function $arr = range(0,6); // printing elements of array foreach ($arr as $a) { echo "$a "; } ?> |
输出
1 | 0 1 2 3 4 5 6 |
例子2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php // creating array with elements from 0 to 100 // with difference of 20 between consecutive // elements using range function $arr = range(0,100,20); // printing elements of array foreach ($arr as $a) { echo "$a "; } ?> |
输出
1 | 0 20 40 60 80 100 |
例子3
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php // creating array with elements from a to j // using range function $arr = range('a','j'); // printing elements of array foreach ($arr as $a) { echo "$a "; } ?> |
输出
1 | a b c d e f g h i j |
例子4
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php // creating array with elements from p to a // in reverse order using range function $arr = range('p','a'); // printing elements of array foreach ($arr as $a) { echo "$a "; } ?> |
输出
1 | p o n m l k j i h g f e d c b a |
参考