» Birthday Bundle - Over $400 worth of Envato files for just $20

PHP: Usage of Range() Function (Alphabetical & Numerical Output)

Posted on September 2, 2008, Filled under PHP,  Bookmark it

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:

php-alphabetical-chars

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!

Get our RSS Feed!

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)