Hướng dẫn
Quảng cáo

Hàm range() trong PHP

Hướng dẫn cách sử dụng hàm range() về mảng trong lập trình PHP

Tác dụng của hàm range()

The range() function creates an array containing a range of elements.

The following table summarizes the technical details of this function.

Return Value: Returns an array of elements from start to end, inclusive.
Version: PHP 4+


The basic syntax of the range() function is given with:

sort(start, end, step);

The following example shows the range() function in action.

// Creating range of numbers
$numbers = range(0, 5);


The range() function accepts the following parameters.

Parameter Description
start Required. Specifies the first value of the sequence.
end Required. Specifies the end value of the sequence.
step Optional. Specifies the increment to be used between the elements in the sequence. It should always be a positive number. If not specified, step will default to 1.

More Examples

Here're some more examples showing how range() function actually works:

The following example demonstrates how to get the sequence of characters between "a" to "z".

// Creating range of letters
$letters = range("a", "z");

// Printing each value using loop
foreach($letters as $letter){
    echo $letter . "<br>";

Note: Character sequence values are limited to a length of one. If string of length greater than one is entered, only the first character is used (e.g., if "hp" is specified "h" will be used).

The following example creates a range of numbers using a floating-point number step.

//  Creating range of numbers using step
$numbers = range(1, 10, 0.5);

// Printing each value using loop
foreach($numbers as $number){
    echo $number . "<br>";

Bài viết này đã giúp ích cho bạn?

Bài viết mới