MoFish Posted April 28, 2015 Share Posted April 28, 2015 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 More sharing options...
Ch0cu3r Posted April 28, 2015 Share Posted April 28, 2015 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 } Link to comment https://forums.phpfreaks.com/topic/295905-looping-around-form-array-values/#findComment-1510156 Share on other sites More sharing options...
MoFish Posted April 28, 2015 Author Share Posted April 28, 2015 Thank you Ch0cu3r, worked a treat! Link to comment https://forums.phpfreaks.com/topic/295905-looping-around-form-array-values/#findComment-1510190 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.