PHP: Usage of Range() Function (Alphabetical & Numerical Output)
Posted on September 2, 2008, Filled under PHP,
Bookmark it
Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.
Hi,
In this tutorial you will see some usage examples of the function range(). They are very effective when you need to create a range of elements. For instance let’s say you need to list some content using an alphabetical search. Here’s a way to do it:
<?php
/*
Alternative array
array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
*/
$non_alpha = array('#');
$alphabetical_array = range('a','z');
$final_array = array_merge($non_alpha, $alphabetical_array);
function AddLinks($letter)
{
$title = strtoupper($letter);
$a = "<a href='alpha_search.php?letter=".$letter."'>".$title."</a>";
return($a);
}
// Use array_map to modify the array by adding the links
$format_array = array_map("AddLinks", $final_array);
echo implode(" | ", $format_array);
?>
Our code will nicely output the alphabetical navigation links with the URL for each letter:
![]()
Other examples of range() usage:
<?php
// 1, 2, 3, 4, 5, 6 ... 30
$sample_one = range(1,30);
echo implode(", ", $sample_one)."<br />";
/*
Start with 50, up to 200 (increment by 10)
50, 60, 70, 80, 90 ... 200
*/
$sample_two = range(50, 200, 10);
echo implode(", ", $sample_two)."<br />";
// 20, 19, 18, 17, 16 .. 3, 2, 1
$sample_three = range(20, 1);
echo implode(", ", $sample_three)."<br />";
?>
Note: This range() function returns elements from low to high, but if low > high then the sequence will be from high to low.
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- September 2, 2008
- article by Gabriel C.
- Leave a reply!
Sponsors
Related Posts
-
PHP: How to select a random value from an array using a specified rangeat September 20, 2008
-
PHP: Make an Alphabetical Selection from Elements of an Arrayat October 5, 2008
-
How to make an alphabetical searchat August 30, 2008
-
Creating the array_isearch() Functionat November 8, 2008
-
PHP: Equivalent of trim() Function for Arraysat October 5, 2008 with 2 comments
