Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Enhancing a Simple PHP Application Paginating a List: Controller Calculating Shirts from Page Number

Leigh Maher
Leigh Maher
21,830 Points

Ok to use this calculation?

Before I watched Randy write out the formula to calculate the $start variable, I tried it myself and came up with a different approach but it seems to work fine. Any drawbacks to writing it this way?

$start = (($current_page * $products_per_page) - $products_per_page) + 1;

Instead of looking at the last one from the previous page, I've done the same calculation as you do for the $end variable and then subtract the number of products per page, and add one.

4 Answers

Hi Leigh,

Your formula and Randy's formula are mathematically equivalent. Both formulas should always produce the same $start value for any given $current_page and $products_per_page values. Which one you use would then come down to personal preference or whichever one seems more intuitive to you.

I don't know what your math level is but I can try to outline why they're equivalent using the distributive rule in mathematics. Here's a link if you're unfamiliar with it: http://www.themathpage.com/alg/distributive-rule.htm

// Randy's formula:
$start = (($current_page - 1) * $products_per_page) + 1

// If you distribute the $products_per_page variable through the parentheses using the distributive rule:
$start = ($current_page * $products_per_page - 1 * $products_per_page) + 1

// Simplifying:
$start = ($current_page * $products_per_page - $products_per_page) + 1

// This is the same as your formula.
Leigh Maher
Leigh Maher
21,830 Points

That's great. Thanks Jason.

I don't see why that would not work. I would put it in the program and test it.

Leigh Maher
Leigh Maher
21,830 Points

Hi Ted, Yes, it does work fine. Just wondering if it might have potential issues done this way?

$end = $currentPage * $productsPerPage; $start = $end - $productsPerPage + 1;