Jump to content

While loop in PHP


fayerie13

Recommended Posts

Hi there, I am new in coding in PHP and I have to do the following below:

 

Using a while loop, I have to increase the driving speed if it is below 120 based on the following conditions

 

○ If the current speed is less than 60, increase it by 30 and echo / print “Your current speed is [$currentSpeed] and you are driving within an urban area”

○ If the current speed is less than 100 and greater than or equal to 60, increase it by 20 and echo / print “Your current speed is [$currentSpeed] and you are driving outside an urban area”

○ If the current speed is less than 120 and greater than or equal to 100, increase it by 10 and echo / print “Your current speed is [$currentSpeed] and you are driving on a freeway”

 

I currently have the following code below:

 

<html>

<head>
<?php
$currentSpeed = 0;
$speed = 0;
 
while ($currentSpeed < 120) {
if ($speed < 60){
$speed + 30;
echo "Your current speed is $currentSpeed and you are driving within an urban area.<br>";
}
elseif ($speed < 100 and >=60) {
$speed + 20;
echo "Your current speed is $currentSpeed and you are driving outside an urban area.<br>"
 
else ($speed < 120 and >=100){
$speed + 10;
echo "Your speed is less $currentSpeed and you are driving on a freeway.";
}
}
?>
</body>
</html>
 
Am i on the right track?
Link to comment
Share on other sites

When you write code, you have to adhere to the exact syntax rules. Something like “$speed < 100 and >=60” may be understandable for humans as a colloquialism, but it neither exists in mathematics nor in PHP. The “and” operator connects two logical expressions, but “>= 60” is no expression of any kind. It's a fragment of a comparison. Actually, “and” has a different purpose in PHP. It has a very low precedence and is used primarily for the control flow (do X, and if that succeeds, do Y). The logical operator you're looking for is “&&”.

...
elseif ($speed >= 60 && $speed < 100)
...

Your “$speed + ...” expressions have no effect at all. They yield a result, but you don't do anything at all with that result. If you want to change the $speed variable, you need an assignment:

$speed = $speed + 10;

Or shorter:

$speed += 10;
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.