0

These are the post variables.

How can I put these in loop?

Where 'master_customer_id' and 'firstname' are the name attributes and the array in them is the values retrieved and I need to save these values to the database.

Values are dynamic, means to say array could go upto any number, here I'm just saying 3 key value pairs.

Thank you in advance.

  array
  'master_customer_id' => 
    array
      0 => string '1' (length=1)
      1 => string '1' (length=1)
      2 => string '1' (length=1)
  'firstname' => 
    array
      0 => string 'a' (length=1)
      1 => string 'a' (length=1)
      2 => string '' (length=0)

I am also adding the form

<?php 

for($i=1;$i<=3;$i++){            
?>

    <input type="hidden" name="master_customer_id[]" value="1" />
First Name: <input type="text" value="" name="firstname[]"/><br/>

<?php  }  ?>
3
  • What exactly do you want to retrieve from the array? Commented Apr 8, 2013 at 7:11
  • 1
    Use foreach to loop through arrays. You can nest them. Commented Apr 8, 2013 at 7:12
  • Values are dynamic, means to say array could go upto any number then how are you going to save them in database columns? Please provide a hint of your database schema Commented Apr 8, 2013 at 7:12

3 Answers 3

1
for ($i = 0; $i < count($_POST['master_customer_id']); $i++) {
  echo $_POST['master_customer_id'][$i];
  echo $_POST['firstname'][$i];
}

or

foreach ($_POST['master_customer_id'] as $key => $value) {
  echo $value;
  echo $_POST['firstname'][$key];
}
Sign up to request clarification or add additional context in comments.

Comments

1

If it is guaranteed that you have the same number of master_customer_id and firstname, you can loop it like this:

if (isset($_POST['master_customer_id'])) {
  for ($i = 0; $i < count($_POST['master_customer_id']; $i++) {
    $customer_id = $_POST['master_customer_id'][$i];
    $firstname = $_POST['firstname'][$i];
  }
}

2 Comments

"If it is guaranteed that you have the same number of master_customer_id and firstname" -- "Values are dynamic, means to say array could go upto any number"
but you have the same number of master_customer_id and firstname. Or you could have like 5 master_customer_id but just 2 firstname?
1
foreach($array as $key => $value)  
{  
    foreach ($value as $key1 => $value1)
    {   
        echo $value1;  
    }  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.