Servo Sweep with conditions

Your servo is being told to go to pos 0 and then move step by step to pos 180

Which happens in a if block.

this tells your servo to go to pos 180 and then move step by step to pos 0

Which happens in the else block.

So what ever reading you get it just move back forth!

Not true.

@OP:
You need to put each { on a new line, and use Tools + Auto Format to properly/consistently indent your code. Then, you need to add some Serial.print() and Serial.println() statements to print out the values read from the sensor.

         Serial.println(analogRead(2));  
         delay(100);
         int analogValue2 = analogRead(2);

The value that you are printing is NOT the value that you are acting on. While they should be relatively close to the same value, that is true only if your sensor is working correctly. Why not make life easy, though, and print the value that you make decisions on?

Also, you are the only one that can see the output you are getting now, so you are the only one that can solve the problem. Share the output (after you fix it) and the modified code if you want us to help.