ttmt Posted January 30, 2009 Share Posted January 30, 2009 If I had a simple form like - I would have 2 arrays, title[], caption[] <p> <input type="text" name="title[]" /> <input type="text" name="caption[]" /> </p> <p> <input type="text" name="title[]" /> <input type="text" name="caption[]" /> </p> <p> <input type="text" name="title[]" /> <input type="text" name="caption[]" /> </p> <p> <input type="text" name="title[]" /> <input type="text" name="caption[]" /> </p> I can access one of these arrays using foreach($_POST['title'] as $key => $value){ //code here } Is it possible to access both arrays in the same foreach loop. Both the arrays information will be placed in the same DB table so I need a way of putting it on the same row Something like foreach($_POST['title] as $key = > $value && $_POST['caption'] as $key => $value2){ $query = "INSERT INTO table (title, caption) VALUES ('{$input}', '{$value2}')" $result = mysql_query($query); } Quote Link to comment https://forums.phpfreaks.com/topic/143174-using-foreach-loop-for-two-arrays/ Share on other sites More sharing options...
gizmola Posted January 30, 2009 Share Posted January 30, 2009 Look at the array functions. There are a variety of ways you can combine two arrays together, and of course you could probably write the code to do this manually i'm betting. Once you have one array, your single foreach will work. Quote Link to comment https://forums.phpfreaks.com/topic/143174-using-foreach-loop-for-two-arrays/#findComment-750945 Share on other sites More sharing options...
ttmt Posted January 31, 2009 Author Share Posted January 31, 2009 <?php $arr1 = array(1,2,3,4); $arr2 = array("one","two","three","four"); $arr3 = array(); for($i=0;$i<=count($arr1)-1;$i++){ array_push($arr3, $arr1[$i]); array_push($arr3, $arr2[$i]); } ?> I can merge the two arrays together in the correct order but then the array will be twice the size it should be. Code that I want to run 4X will be run 8X - I'm I right ? Quote Link to comment https://forums.phpfreaks.com/topic/143174-using-foreach-loop-for-two-arrays/#findComment-751231 Share on other sites More sharing options...
sasa Posted January 31, 2009 Share Posted January 31, 2009 <?php foreach($_POST['title'] as $key => $value){ //code here $caption = $_POST['caption'][$key]; echo "Title is $value and caption is $caption<br />\n"; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/143174-using-foreach-loop-for-two-arrays/#findComment-751237 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.