Navigate
Home
ArticleWiki
Forum
Journal
Search
Newsletter
Links
Tech News
expertsrt.com
Welcome Guest.
Username:

Password:

Remember me

new to php,please help regarding loops
Welcome, Guest. Please login or register.
January 08, 2009, 11:27:57 PM
11313 Posts in 1251 Topics by 508 Members
Latest Member: pissematbox
Experts Round Table Network  |  Serverside Technology  |  PHP  |  new to php,please help regarding loops « previous next »
Pages: [1]
Author Topic: new to php,please help regarding loops  (Read 819 times)
malikvibhor

Offline Offline

Posts: 4


« on: January 27, 2008, 07:50:10 AM »

hello,
i m vibhor malik
i m new to php5 and learning it by myself using beginning php5 wrox publisher
as i am on loops chapter i did conditions chapter
in the loops chapter i did while,do while,for loop
i read all examples in the chapter,done it practically.
but there is one example in which it finds wether a no. is prime or not using do while loop
i understood the program fully and can do it
but when i change it to for loop and write it myself it doesnt work
so i m writing the program which was in book using do while loop then i will write program which i wrote using for loop which didnt worked.

program using do while loop which was in book>>>>>


<html>
<head><title></title></head>
<body>
<?php
if ( isset ( $_POST ['posted' ] ) )  {
$count=2;
do
{
$remainder=$_POST['Guess']%$count;
$count=$count+1;
}
while($remainder!=0 &&  $count < $_POST['Guess'] ) ;
if (  ( $count < $_POST ['Guess']  ) || ($_POST ['Guess '] == 0 ) )  {
echo "your no. is not prime";
}
else {
echo "your no is prime";
}
}
?>
<form method="POST" action="prime1.php">
<input type="hidden" name="posted" value="true">
what is your number for checking prime:
<input type="text" name="Guess">
<br>
<input type="submit" value="submit">
<br>
</form>
</body>
</html>

as i said i understood the functioning of program fully

so now i writing the program which i made using for loop>>>>

<html>
<head><title></title></head>
<body>
<?php
if ( isset ( $_POST ['posted' ] ) )  {

for ($count=2;$count<$_POST['Guess'];$count++)
{
$remainder=$_POST['Guess']%$count;
}

if (  ( $count < $_POST ['Guess']  ) || ($_POST ['Guess'] == 0 ) )  {
echo "your no. is not prime";
}
else {
echo "your no is prime";
}
}
?>
<form method="POST" action="prime1.php">
<input type="hidden" name="posted" value="true">
what is your number for checking prime:
<input type="text" name="Guess">
<br>
<input type="submit" value="submit">
<br>
</form>
</body>
</html>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

now please tell me why my program is not working
how should i progress to think a better functionality to make my programs woking
in total where i m lacking
i think i dont have a sense for programming but nothing is impossible in this world
please help me

thnx a lot
regards
vibhor malik
Logged
malikvibhor

Offline Offline

Posts: 4


« Reply #1 on: January 28, 2008, 06:51:54 AM »

and now i tried this piece of code using for loop but again not working
check it out>>>



<html>
<head>
<title>
</title>
</head>
<body>
<form method="POST" action="prime2.php">
<input type="hidden" value="true" name="posted">
enter no:
<input type="text" name="Guess">
<br>
<input type="submit" value="submit">
</form>
<?php
if (isset($_POST['posted'])) {
for ($count=2;$count<$_POST['Guess'];$count++)
{
$remainder=$_POST['Guess']%$count;
}
if($remainder==0 || $count<$_POST['Guess']) {
echo "ur no is not prime";
}
else {
echo " ur no is prime";
}
}
?>
</body>
</html>
Logged
GrandSchtroumpf
Mentor

Offline Offline

Posts: 411



« Reply #2 on: January 28, 2008, 08:30:05 AM »

<html>
<head>
<title>
</title>
</head>
<body>
<form method="POST" action="prime2.php">
<input type="hidden" value="true" name="posted">
enter no:
<input type="text" name="Guess">
<input type="submit" value="submit">
</form>
<?php

if (isset($_POST['posted'])) {
   
   // You must initialize $remainder to a non-zero value !!!
   // Declare $remainder outside the "for" statement to be sure it's in scope when you use it in you "if" statement.
   // Looks like variable scope is not enforced in PHP... i prefer to stay on the safe side and keep my good coding habbits.
   $remainder = 1;
   
   // Don't forget to exit the loop as soon as $remainder is null.
   for ($count = 2; $remainder != 0 && $count < $_POST['Guess']; $count++) {
      $remainder = $_POST['Guess']%$count;
      // Some echo added here to see what's going on...
      echo "dividing by $count => remainder = $remainder <br>";
   }
   
   // You only need to check if $reminder is null.
   if ($remainder == 0) {
      echo $_POST['Guess'] . " is not prime";
   }
   else {
      echo $_POST['Guess'] . " is prime";
   }
}
?>
</body>
</html>
Logged
malikvibhor

Offline Offline

Posts: 4


« Reply #3 on: January 28, 2008, 11:57:17 PM »

thanks a lot sir for your support
i got it what u explained
as i was not knowing that
if for loop starts from $count=2 we can add $remainder also in that

i m not so pro  by thinking logics as a programmer
please can u tell me
when i start a program
how should i think for the logic to make my program working

ok i will give u one more example
i tried to take this kind of output using for loop


1
11
111
1111
11111

and the piece of code i made was>>>>>>

<html>
<head>
<title>
</title>
</head>
<body>
<?php

for ($i=0;$i<5;$i++) {

     for ($j=0;$j<$i;$j++)  {

      echo "1";
      }
      }
      ?>


</body>
</html>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

i did this bcoz first for loop will make 5 lines like this
1
1
1
1
1

the second for loop will make a triangle bcoz that for loop is inside the first for loop
and echo 1 is for showing 1's in output and in first for loop i used $i<5 bcoz there are 5 lines in the output

but where am i wrong?
here also i m lacking logic
how do i increase my logic level?

thnx a lot
regards
vibhor malik
Logged
GrandSchtroumpf
Mentor

Offline Offline

Posts: 411



« Reply #4 on: February 01, 2008, 07:28:37 PM »


You can start by using consistent indentation, and using some spaces to make your code easier to read.

Then, you can give your variables long meaningful names...
I never use $i and $j for instance because it makes it harder to do a search/replace.

I took that habit when coding in C which is a compiled language, so, spaces, long variable and function names don't increase the byte-size of your program.

When using loops, don't hesitate to add some "echo" statements to monitor the value of your counters.

Keep it simple and clean as much as you can.  That's the basic rule.

Here is your modified code:

Code:
<html>
<head>
<title>
</title>
</head>
<body>
<?php

for ($outer = 0; $outer < 5; $outer++) {

echo " outer = $outer : ";

for ($inner = 0; $inner < $outer; $inner++)  {

echo " (inner = $inner)  ";

}

echo "<br>";

}

?>
</body>
</html>
Logged
VGR
Mentor

Offline Offline

Posts: 684



WWW
« Reply #5 on: February 02, 2008, 02:11:01 PM »

and the DOCTYPE ? :-)
Logged

techie overlord, answers all kind of questions on http://www.europeanexperts.org
rdivilbiss
Governing Council Member
*
Offline Offline

Posts: 414



WWW
« Reply #6 on: February 03, 2008, 11:02:36 AM »

Welcome to ERT, vibhor,

I offer some changes for better functionality and to protect against malicious input.

Live Example: http://www.cafesong.com/ert/guess_prime_numbers_for_loop.php  (Also checks for Integer overflow.)

Code
Language: php (GeSHi-highlighted)
<?php
// Separate the PHP from the HTML.  Use a result message to bridge the gap.
 
 
/*
  if (isset($_POST['posted'])) {
  You do not need a hidden form field to tell if the action is a form POST.
  That is a waste of characters, use the REQUEST_METHOD.
*/

if ($_SERVER['REQUEST_METHOD']=="POST") {
/* Using $_POST['Guess'] everytime you need to access the posted value is
  time consuming, relative to getting the value one time and setting a
  variable to hold the value.
*/

$guess = $_POST['Guess'];

/* Also, since the form user could post anything, including malicious characters
  in the Guess form field...you need to filter the posted value to ensure only
  valid values are accepted and processed.  Failing to do so at the least makes your
  code suseptable to XSS attacks.
*/


$regExPattern = "/^([-]*[1-9]+[0-9]*)|([0])$/"; // Accept only Integers
preg_match($regExPattern, $guess, $arr);
if (!empty($arr)) {
$guess = $arr[0];

if ($guess<2) {
$result = "Your number (".$guess.") is not prime.";
}else{
$result = "Your number is prime.";
for ($count=2;$count<$guess;$count++) {
$remainder=$guess%$count;
//echo "Guess: ".$guess." Count: ".$count." Remainder: ".$remainder."<br>";
if (($remainder==0) && ($count!=$guess)) {
$result = "Your number (".$guess.") is not prime.";
                                       $count = $guess; // short circuit the for loop...there is no need to check further values.
}
}
}
}else{
$result = "Please enter an Interger value in the text box.";
}
} else {
$result = "Please enter your guess.";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
 <title>Guess Prime Numbers</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<p><? echo $result; ?></p>
<form method="POST" action="prime1.php">
 <p>What is your number for checking prime:&nbsp;<input type="text" name="Guess"></p>
 <p><input type="submit" value="submit"></p>
</form>
</body>
</html>
« Last Edit: February 03, 2008, 11:32:48 AM by rdivilbiss » Logged

Rod
GrandSchtroumpf
Mentor

Offline Offline

Posts: 411



« Reply #7 on: February 09, 2008, 07:25:59 PM »

>>          $count = $guess; // short circuit the for loop...there is no need to check further values.
Yuk!  Use a "break" statement instead of hacking the counters.
Logged
rdivilbiss
Governing Council Member
*
Offline Offline

Posts: 414



WWW
« Reply #8 on: February 09, 2008, 08:57:47 PM »

>>          $count = $guess; // short circuit the for loop...there is no need to check further values.
Yuk!  Use a "break" statement instead of hacking the counters.

I agree whole heartedly. I just pop from language to language and couldn't remember the correct command. 

replace: $count = $guess

with break;
Logged

Rod
malikvibhor

Offline Offline

Posts: 4


« Reply #9 on: February 16, 2008, 04:48:21 AM »

Hello Rod,

Thanks a lot for such a good and secure code, but as i mentioned i m new to PHP
i understood only few terms of your code.
Sorry to say this but i need time to go that further high level coding.
i m learning myself from 'Begining php5 wrox edition'
and i didn't found any line in that book like

if ($_SERVER['REQUEST_METHOD']=="POST") {

so i used
if(isset ($_POSt['posted'])) {

so it would be so kind of you if you would tell me what book should i refer to gain further good knowldge for PHP.

thanks a lot
vibhor
Logged
rdivilbiss
Governing Council Member
*
Offline Offline

Posts: 414



WWW
« Reply #10 on: February 16, 2008, 12:11:57 PM »

Hello Rod,

Thanks a lot for such a good and secure code, but as i mentioned i m new to PHP
i understood only few terms of your code.
Sorry to say this but i need time to go that further high level coding.
i m learning myself from 'Begining php5 wrox edition'
and i didn't found any line in that book like

if ($_SERVER['REQUEST_METHOD']=="POST") {

so i used
if(isset ($_POSt['posted'])) {

so it would be so kind of you if you would tell me what book should i refer to gain further good knowldge for PHP.

thanks a lot
vibhor

The mthod in the WROX tutorial of using a hidden form field to later check for a POST is a waste of HTML, possibly subject to abuse, and simply not necessary.

When the user's browser requests a page from the server the two most common requests are GET and POST.

PHP running on the web server knows how the page request was made, and that information is available with $_SERVER['REQUEST_METHOD'].

Many times a web developer will write one page which both displays a form but also processes the form if the user submits the form.

If the HTML for the form METHOD is POST then when the form is submitted, the field name/value pairs are passed in the headers and $_SERVER['REQUEST_METHOD'] will equal POST.

If the HTML for the form METHOD is GET then when the form is submitted, the field name/value pairs are passed on the URL and $_SERVER['REQUEST_METHOD'] will equal GET.

In programming there are often many ways to achieve a goal.  In the case of determining if a form was submitted or not, checking $_SERVER['REQUEST_METHOD'] is the better practice.

Logged

Rod
rdivilbiss
Governing Council Member
*
Offline Offline

Posts: 414



WWW
« Reply #11 on: February 16, 2008, 01:33:13 PM »

An example set of pages to demonstrate http methods re:forms.

http://www.cafesong.com/ert/form-method-landing-page.php
Logged

Rod
Pages: [1]
« previous next »
    Jump to: