range()函数是PHP中的一个内置函数,用于在给定范围内(从低到高)创建任何类型的元素数组,例如整数、字母表,即列表的第一个元素被视为低,最后一个元素被视为高。
null
语法:
array range(low, high, step)
参数: 此函数接受以下三个参数:
- 低: 它将是range()函数生成的数组中的第一个值。
- 高: 它将是range()函数生成的数组中的最后一个值。
- 步骤: 当范围中使用的增量及其默认值为1时,将使用该值。
返回值 :它返回从低到高的元素数组。
例如:
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 :
<?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 " ; } ?> |
输出:
0 1 2 3 4 5 6
方案2 :
<?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 " ; } ?> |
输出:
0 20 40 60 80 100
方案3 :
<?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 " ; } ?> |
输出:
a b c d e f g h i j
方案4 :
<?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 " ; } ?> |
输出:
p o n m l k j i h g f e d c b a
参考: http://php.net/manual/en/function.range.php
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END