1 Replies - 329 Views - Last Post: 26 September 2012 - 08:36 AM Rate Topic: -----

#1 ettedo2000  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 26-September 12

question on loop in php

Posted 26 September 2012 - 08:22 AM

Hello,
I want to write a PHP page that takes 3 numbers (starting,ending, incrementing) inputted by the user and increments it accordantly. If the starting number is smaller than the ending number increment as addition. If starting number is larger than ending number increment in subtraction. If both of those conditions are false, send an error to the web browser.

Now the user can input in increment field +number or -number.(ex: starting # 50 ending number # 10 Increment # -5)

I have a problem with that when the user adds a -/+ in front of the increment # I get stuck in a endless loop and even though the -Increment should subtract it is actually adding.

I have included my loop with this post. I hope someone can point me into the right direction.

<?php
$NumberI = $_POST["NumberI"];  
$NumberII = $_POST["NumberII"];	
$NumberInc= $_POST["NumberInc"];
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Lab005 Html Page</title>
</head>

<body>

<?php 
	// Functions
	echo "<p> The Starting Numbers you entered is: $NumberI</p>\n";
	echo "<p> The Ending Numbers you entered is: $NumberII</p>\n";
	echo "<p> The Increment Numbers you entered is: $NumberInc</p>\n";
	
	while ($NumberInc > 0 ){
		if ($NumberI < $NumberII){
			while ($NumberI < $NumberII)
			$NumberI = $NumberI + $NumberInc;											
			echo "<p>$NumberI</p>";	
			}
		}
		else if (!$NumberI < $NumberII){
		echo "<p> incorrect input </p>";
		}
	}
	
	while ($NumberInc <0){
		if ($NumberI > $NumberII){
			while ($NumberI > $NumberII){
			$NumberI = $NumberI - $NumberInc;											
			echo "<p>$NumberI</p>";
			}
		}
		else if ($NumberI < $NumberII){   
		echo "<p> Incorrect Input </p>";
		}
	}
	
		
?>
</body>
</html>



Is This A Good Question/Topic? 0
  • +

Replies To: question on loop in php

#2 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2993
  • View blog
  • Posts: 10,343
  • Joined: 08-August 08

Re: question on loop in php

Posted 26 September 2012 - 08:36 AM

I would take the absolute value of the increment and then if the ending number is less than the starting number I'd multiply increment by -1. That way you remove most error possibilities. You still have to check for an increment of zero though.

By the way, this is unnecessary and bad form:
$x = $_POST['x'];

$_POST is a variable too! You don't need to copy from it just because it's global. Doing so sets you up for problems later on, especially if you use deprecated mysql* functions.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1