Amending variables in a $_POST array - sense check needed

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
sjk1000
Forum Commoner
Posts: 26
Joined: Tue Nov 11, 2008 8:50 am

Amending variables in a $_POST array - sense check needed

Post by sjk1000 »

Hi all
I want to convert variables in a $_POST array into money format before I process them. I'm not entirely confident about accessing arrays in this way. I know the following loop hangs. Can someone tell me where I'm going wrong please?
Any help is very much appreciated.
Thanks, Steve

Code: Select all

for ($x=0; count($_POST['price']); $x++)
        {
        if ($_POST['price'][$x] != '')
            {
            $_POST['price'][$x] = money_format('%i', $_POST['price'][$x]);
            }
        }
Last edited by sjk1000 on Wed Dec 10, 2008 7:58 am, edited 2 times in total.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Amending variables in a $_POST array - sense check needed

Post by Eran »

You don't have a stopping condition (you don't compare $x in the second argument of the loop):

Code: Select all

for ($x=0; count($_POST['price']); $x++)
Needs to be:

Code: Select all

for ($x=0; $x < count($_POST['price']); $x++)
Though it's generally better to use foreach when iterating over arrays:

Code: Select all

foreach($_POST['price'] as $key => $price) {
   if ($price != '') {
          $_POST['price'][$key] = money_format('%i', $price);
    }
}
sjk1000
Forum Commoner
Posts: 26
Joined: Tue Nov 11, 2008 8:50 am

Re: Amending variables in a $_POST array - sense check needed

Post by sjk1000 »

Thanks for that pytrin. That works fine now. As soon as I'd posted I noticed I'd forgotten the stopping condition. Need to do some reading on foreach.
Cheers, Steve
:D
Post Reply