Announcement

Collapse
No announcement yet.

Input as array

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Input as array

    I have a form that I want to pass to PHP as an array. Simple enough, but I'd like the array to be:

    Array ( [0] => Array ( 'name' => a 'email' => b ) [1] => Array ( 'name' => c 'email' => d ) )

    Currently my form is:

    Code:
    <form action="" method="post" name="record[]">
    <input type="text" name="record[0][name]"><input type="text" name="record[0][email]"><br>
    <input type="text" name="record[1][name]"><input type="text" name="record[1][email]"><br>
    <input type="button" class="button" value="submit">
    </form>
    but that passes 'name' and 'email' as [name],[email] which doesn't display the results that I'm looking for when I do a foreach().

    Ultimately, I want to cycle through each record using PHP and print:

    name: a
    email: b

    name: c
    email: d

    Suggestions?

    Thanks in advance.

  • #2
    PHP Code:
    <?php
    $echo 
    ="";
    for (
    $x 0$x <= count($_REQUEST['record'])-1$x++) {
        
    $echo .= "Name: {$_REQUEST['record'][$x]['name']} </br>Email: {$_REQUEST['record'][$x]['email']}</br></br>";

    echo 
    $echo;

    ?>
    HTML Code:
    <form method="post" >
    	<input name="record[0][name]" type="text" placeholder="Name" />
    	<input name="record[0][email]" type="text" placeholder="Email" /></br>
    
    	<input name="record[1][name]" type="text" placeholder="Name" />
    	<input name="record[1][email]" type="text" placeholder="Email" />
    	<input type="submit"  value="submit">
    </form>

    Comment


    • #3
      Hey sleepydad

      Another option

      PHP Code:

      if(isset($_POST['record'])) {
          
           foreach (
      $_POST['record'] as $record) {
              echo 
      'Name:'.$record['name'].'<br />';
              echo 
      'Email:'.$record['email'].'<br /><br />';
           }

      HTML Code:
      <form action="form.php" method="POST" name="record[]">
      
      <?php
      #Cycle the inputs and change the while loop limiter for the required amount of inputs... yes, I'm too lazy to hand code too much ;)
      $counter = 0;
      	while ($counter < 2) {
      		echo '<input placeholder="Name '.$counter.'" type="text" name="record['.$counter.'][name]"><input placeholder="Email '.$counter.'" type="text" name="record['.$counter.'][email]"><br>';
      	$counter++;
      	}
      ?>
      
      <input type="submit" class="button" value="submit">
      </form>


      Smile, It Confuses People...

      XHTML | CSS | Tutorials | Refferences

      Comment

      Working...
      X