Jump to content

Looping Around Form Array Values


Go to solution Solved by Ch0cu3r,

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

  • Solution

 

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
}
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.