phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP - number: Generating a Number Range

Tag: number, number range   Category: PHP Application
post: 16 Mar 2008 read: 184


PHP Number tips - part 1: If you have two endpoints and want to generate a list of all the numbers between them, so you can use PHP's range( ) function such as:

<?php
//define range limits
$x = 10;
$y = 36;

//generate range as array
//result: (10, 11, 12...35, 36)
$range = range($x, $y);
print_r($range);
?>

The range( ) function accepts two arguments. There are a lower limit and an upper limit. Beside that, it returns an array containing all the integers between those limits and you can also create a number range that steps over particular number by passing the step value to the function as a third, optional argument.


<?php
//define range limits
$x = 10;
$y = 30;

//generate range as array
//contains every third number
//result: (10, 13, 16, 19, 22, 25, 28)
$range = range($x, $y, 3);
print_r($range);
?>

A simple application of range( ) function is to print a multiplication table. Beneath, you can see a list illustrates how to do print a multiplication table, by generating all numbers between 1 and 10, then using the list to print a multiplication table for the number 5:


<?php
//print multiplication table
foreach (range(1, 10) as $num) {
  echo "5 x $num = " . (5 * $num) . "\n";
}
?>



| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting