Page 1 of 1

Nesting Control Structures?

Posted: Mon Sep 14, 2009 6:58 pm
by Spoooon
Hi I am basically brand new to php. Right now, I'm trying to create a script that

1. assigns some information inputted by the user to a variable
2. Checks to see if it is a string
3. If it is a string it prompts the user to input a number
4. if it is a number, it performs a counting algorithm

I think i made a mistake with the control structures. Either I'm nesting them wrong or I'm using the wrong ones.

Please check out my code, thanks.

Code: Select all

 
    <?php
 
        $count = $_POST['count'];
        
        if (is_string($count)
        { 
        echo "That is not a number!";
        }
        
        else
        {       
            while ($count <=1000)
            {
            echo "$count <br />";
            $count = $count *(-2);
            }
        }
    ?>
 

Re: Nesting Control Structures?

Posted: Mon Sep 14, 2009 7:13 pm
by Christopher
A confusing thing about languages like PHP is that it will convert strings to numbers (and vice-versa) based on context. So the $_POST array contains all strings because that's what HTTP considers them. Some of those strings may contain numeric data ... and PHP will convert it on-the-fly for you.

So probably something like this:

Code: Select all

        $count = $_POST['count'];
        
        if (is_numeric($count))
        {       
            while ($count <=1000)
            {
            echo "$count <br />";
            $count = $count *(-2);
            }
        }
        else
        { 
            echo "That is not a number!";
        }
It is a general practice to do the error check for the success condition. Doing that puts the code you want to be executed at the top and the error condition in the else.

Re: Nesting Control Structures?

Posted: Mon Sep 14, 2009 7:37 pm
by Spoooon
Thanks for the help.

I'll try it out.

Re: Nesting Control Structures?

Posted: Tue Sep 15, 2009 3:21 pm
by peterjwest
By the way, Spoooon, your code had a missing end bracket on line 6. If you didn't see a message about it you should enable php error reporting:
http://simonmcmanus.wordpress.com/2007/ ... or-a-page/