1
\$\begingroup\$

I've been researching if this is possible, but I've drawn a blank, I'm wondering if it's possible to optimize these for and if statements together?

<?php
// calculate total number of pages
$total_pages = ceil($total_rows / $records_per_page);

// range of links to show
$range = 2;

// display links to 'range of pages' around 'current page'
$initial_num = $page - $range;
$condition_limit_num = ($page + $range)  + 1;
?>
    <ul class="pagination margin-zero">
<?php if ($page>1) : ?>
        <li>
            <a href='<?php echo $page_url; ?>' title='Go to the first page.'>
                First Page
            </a>
        </li>
<?php endif; ?>

<?php
for ($x = $initial_num; $x<$condition_limit_num; $x++) :
    if (($x > 0) && ($x <= $total_pages)) :
        if ($x == $page) : ?>
        <li class='active'>
            <a href="#"><?php echo $x; ?> <span class="sr-only">(current)</span></a>
        </li>
        <?php else : ?>
        <li>
            <a href='<?php echo $page_url; ?>page=<?php echo $x; ?>'><?php echo $x; ?></a>
        </li>
        <?php
        endif;
    endif;
endfor;
?>

<?php if ($page<$total_pages) : ?>
        <li>
            <a href='<?php echo $page_url; ?>page=<?php echo $total_pages; ?>' title='Last page is <?php echo $total_pages; ?>'>
                Last Page
            </a>
        </li>
<?php endif; ?>

    </ul>
\$\endgroup\$
  • 1
    \$\begingroup\$ Please provide the full actual code that runs on your page. \$\endgroup\$ – Your Common Sense Oct 30 '18 at 11:32
  • 1
    \$\begingroup\$ @YourCommonSense I've edited the post, thanks. \$\endgroup\$ – Casper Oct 30 '18 at 11:39
2
\$\begingroup\$

The main loop code lacks the prior validation. So in the business logic part

  • verify that $x is positive. if not, make it the least number possible (1 I suppose)
  • verify that $x is <= $total_pages. Make them equal otherwise
  • prepare the page numbers in the form of array using $pages = range($initial_num, $condition_limit_num);

So you will have a single loop with a single condition

<?php foreach ($pages as $x): ?>
    <?php if ($x == $page) : ?>
        <li class='active'>
            <a href="#"><?= $x ?> <span class="sr-only">(current)</span></a>
        </li>
    <?php else: ?>
        <li>
            <a href="<?= $page_url ?>page=<?= $x ?>"><?= $x ?></a>
        </li>
    <?php endif ?>
<?php endfor ?>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.