How would I write this in an If statement?

if $i is either 1 to 4 away from $total_variable then do something

How would I write that in an if statement within a for loop?

This sounds disturbingly like homework. Since you’re not going to learn without doing the work, I’ll give you some pseudo thoughts to work off of. You do that and still have problems, then we’ll help you get over the hump

Steps to run:

  1. You’ll need to setup a basic loop
  2. How do you subtract a value from a variable?
  3. Now how do you take the value from step 2 and compare it to to loop variable?
  4. How do you do a separate condition in which if either part of the statement is true, execute some code.
  5. How would you combine steps 2-4 to look at your two values.

Here’s a hint - you can run this line in four lines of code (if the opening and closing brackets are considered a line of code.

if(($i <= $total_variable+4 && $i >= $total_variable+1) ||
   ($i >= $total_variable-4 && $i <= $total_variable-1)) {
     // do stuff

I think. If I understand you correctly.

There is an even easier way to do this, but I’m not going to give the solution for like someone said if this is a homework assignment, it’s better to do it on your own… :smile:

What does it matter if it’s homework or not? Everyone needs a little nudge every now and again, it’s not like it’s a full program like this.

Also, I should mention I’m not a PHP guy. But I found what @Pepster was talking about pretty easily on Google.

Because like I told my son the other day when I was helping him with his geometry homework - you’re only going to learn if you put in the work. Just being told doesn’t make the content stick.

It’s the same axiom as the old “Give a man a fish, feed him for a day. Teach a man to fish, feed him for a lifetime.”

1 Like

I’ll give a slight nudge.


1 Like

Thanks! Your example worked and I configured my script from it.

No this isn’t for school but something I’ve been working on as a hobby.

It’s a bad way to do it. There were 2 better ways mentioned in this thread, please use them.

I agree with @StarLion 's suggestion. Since it isn’t a school assignment, I’ll go one step further with an example: an expression to describe “x is less than 5 units away from y” is |x - y| < 5" or “abs(x - y) < 5” .