Jump to content

need help with foreach loop :)


manuelV

Recommended Posts

Basically I have this code

 

<?php 
$myInput = $_POST["myInput"]; // these have more than one value to it
$myInput2 = $_POST["myInput2"];

foreach ($myInput as $eachInput ) {
    echo $eachInput ."<br>"; 
}
foreach ($myInput2 as $eachInput2 ) {
    echo $eachInput2 ."<br>"; 
}
?>

This code will input however many values are gathered from the $_POST. Works just fine.

 

But what I need is for there to be one foreach loop, as supposed to two. I need both of those to be in a single foreach. Is there a way of doing this?

 

Reason for this is the values will be inserted into a SQL table, in two different columns. So I need to be able to do it with a single query!

 

Any help is appreciated :)

 

 

Link to comment
Share on other sites

Well assuming they line up (e.g. the first value in myInput goes with the first value in myInput2) you could do something like:

 

$count = 0; foreach ($myInput as $eachInput ) {

  echo $eachInput ."<br>"; 
  echo $myInput2[$count];

  $count++;
}

Link to comment
Share on other sites

Does input2 also have multiple fields?

Yes it does.

 

I managed to get it to work like this

 

<?php
$myInputs = $_POST["myInputs"];
$myInputs2 = $_POST["myInputs2"];
foreach($myInputs as $k=>$eachInput) {
    $eachInput2 = $myInputs2[$k];
    mysql_query("INSERT INTO contactInfo (contactValue, contactType) VALUES ('$eachInput2','$eachInput')");
}
?>

 

:)

Link to comment
Share on other sites

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.