Jump to content

Looping Around Form Array Values


MoFish

Recommended Posts

Hi,

I'm looking for a little guidance on the best way to loop around some form input fields.

I have a form with a few input boxes. I have used the [] on the end of the names in an attempt to get these into an array.

View

<input type="text" class="form-control" id="url[]" name="url[]" placeholder="" value="" />
<input type="text" class="form-control" id="price[]" name="price[]" placeholder="199" value="" />

I'm now trying to get each of the values out and save them to the database.

I assume I need a foreach loop to do this, but am not sure on the best way to do this. I have the following in my controller so far.

Controller

$post_array = array(
   'url' => $_POST['url[]'],
   'price' => $_POST['price[]'],
   'order_id' => '1'
);
$this->order_model->add($post_array); 

 

Any help/guidance would be much appriciated!

Thanks,

MoFish

Link to comment
https://forums.phpfreaks.com/topic/295905-looping-around-form-array-values/
Share on other sites

 

I have the following in my controller so far.

The [] should not in be included in the key for $_POST['url[]'] and $_POST['price[]']. They should be like so

$_POST['url']
$_POST['price']

PHP will automatically convert form values where the field name contains square brackets into a multidimensional array.

 

 

I assume I need a foreach loop to do this,

 

Yes you would need to some form of loop to get their individual values, eg

// loop through urls
foreach($_POST['url'] as $url)
{
   // do something
}

// loop through prices
foreach($_POST['price'] as $price)
{
   // do something
}

If you want to process the url and price together then you could do it with one loop eg

// loop through urls
foreach($_POST['url'] as $k => $value)
{
   $url = $value;
   $price = $_POST['price'][$k];

  // do something
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.