Page 1 of 1

Amending variables in a $_POST array - sense check needed

Posted: Wed Dec 10, 2008 7:45 am
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]);
            }
        }

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

Posted: Wed Dec 10, 2008 7:52 am
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);
    }
}

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

Posted: Wed Dec 10, 2008 8:00 am
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