Looking for a formula

I’m trying to find a one-line formula to calculate the previous number in a sequence wrapping round when it gets to zero, thus keeping the number in the range 1 - 8. I’ve managed to do it when getting the next number but cannot fathom out a formula when subtracting without using a conditional.

This is what I have:

for ($i = 1; $i <= 8; $i++):
  $n = $i % 8 + 1;
  $p = $i - 1;
  if ($p < 1)
    $p = $tot;

I could use a ternary operator but I’d still prefer to do it without a conditional if possible. I can’t help but feel it is possible but my little brain is overheating.

okay, it took me a minute to understand what you’re asking.
It’s a arse-to-elbows mechanism, and I think there’s a better way of doing it, but my brain is failing me at the moment…
$p = (($i+6)%8)+1

1 Like

And for those that try to figure out how i came up with that:

“The desired range is the numbers 1 to 8, wrapping around”
“Modulo wraps things around, but it starts from 0.”
“Okay, so shift the range: 0 to 7. We can add 1 afterwards and get back to where we want to be.”
“Right. So that’s a Modulo 8.”
“Yup. And now we need to shift the array backwards.”
“But the modulo of negative numbers doesnt work that way.”
“Okay, so shift FORWARDS until the cycle lines up again in the way that you want.”
“… 6 steps. Adding 7 to a cycle would be the equivilant of subtracting 1, but we start from 1, so it’s actually adding 6.”
“$i plus 6, modulo 8, add 1.”


Nice one, @m_hutley! :slight_smile: Thanks. I thought of shifting it forwards but my brain went phut.

I am not understanding what you are doing. Is there a real problem you are trying to solve or is this just because? What is the expected output?

In your attempt, there is no $tot and the $n line is unused.

Oops! $tot should be 8, and in the snippet neither $n (next) or $p (previous) are used.

It’s part of a script to loop through a number of images (8 in the example). $i, $n and $p are the current, next and previous images, prefixed by ‘image’ or something similar.

So pagination right?

Sometimes there isnt some super-deep reasoning or use case that you can point at and go ‘ah no heres what you actually mean to do’.

Sometimes people just have a straightforward question, with a straightforward answer.

Kind-of. Part of a slideshow/lightbox affair.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.