Nesting Control Structures?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Spoooon
Forum Newbie
Posts: 5
Joined: Mon Sep 14, 2009 6:15 pm

Nesting Control Structures?

Post 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);
            }
        }
    ?>
 
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Nesting Control Structures?

Post 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.
(#10850)
Spoooon
Forum Newbie
Posts: 5
Joined: Mon Sep 14, 2009 6:15 pm

Re: Nesting Control Structures?

Post by Spoooon »

Thanks for the help.

I'll try it out.
peterjwest
Forum Commoner
Posts: 63
Joined: Tue Aug 04, 2009 1:06 pm

Re: Nesting Control Structures?

Post 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/
Post Reply