Blog de programación, errores, soluciones

Chose Language:
comments
Author: Admin/Publisher |not checked

PHP Range function

PHP Range function creates an array that contains a range of elements from $start to $end.

Example: if my start value is 0 and the $end value is 70 and my step value is 10 the values of my array elements are: 0, 10, 20, 30 ,40, 50, 60, 70.

Descripción
range(mixed $start, mixed $end, number $step = 1): array

Probably you are asking yo why $start and $end are mixed, this is cause the value could be an integer or a string “A” for example.

Function values

Parameters

$start– this is the inicial value in the array.

$end– this could or not be the final value in your array, if we have an iterator that is give us unpair and our parameter $end is pair, for example range(1,10,2) the array elements got as result is 1,3,5,7,9.

$step -(optional) its default value is 1. Its the incremental value inside the iteration. Must be a number.

Returns

Return an array of elements defined by the iteration from $start to $end with $step(step)

Example

Let’s consider different examples: for example, imagine that we have to do a page that is for a bookstore and the owner wants to have all the different letters which the book begin in the header of the page.

We could do the navbar with multiples buttons with the different letters or we could use range with foreach.

First, we need the values from A to Z.

var_dump(range("A","Z"));

We could traverse it now with foreach:

foreach(range("A","Z") as $letra){
	echo $letra;
}
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Como sigue se lo dejo a usted el lector.

Regrettably, range in letters go from A to Z and we can’t use AA or other expression, if you need to do A to AZ or something like that you will need to do it with multiples foreach.

Other Example:

foreach(range(1,10,2) as $numero){
	echo $numero;
}
13579
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments