Jump to content

Using foreach loop for two arrays ?


ttmt

Recommended Posts

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);
}

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/143174-using-foreach-loop-for-two-arrays/
Share on other sites

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.

<?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 ?

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.