rji rji
rji rji

Reputation: 707

How to get the form fields in a single array in PHP

I have a form

<form name="frm_passport" id="frm_passport" action="" method="POST">
  <input name="ws[surname]" id="surname" type="text" value="<?php echo (isset($_POST['ws']['surname']) && $_POST['ws']['surname'] != '') ? $_POST['ws']['surname'] : ''; ?>"/>
  <input name="ws[firstname]" id="firstname" type="text" value="<?php echo (isset($_POST['ws']['firstname']) && $_POST['ws']['firstname'] != '') ? $_POST['ws']['firstname'] : ''; ?>"/> 
  <input name="ws[prevname]" id="prevname" type="text" value="<?php echo (isset($_POST['ws']['prevname']) && $_POST['ws']['prevname'] != '') ? $_POST['ws']['prevname'] : ''; ?>"/>

This is my code after form submit

<?php
if (isset($_POST['Submit']) && $_POST['Submit'] != '') {
$_POST['ws']['surname'] = (isset($_POST['ws']['surname']) && $_POST['ws']['surname']!="")?$_POST['ws']['surname']:'';
$_POST['ws']['firstname'] = (isset($_POST['ws']['firstname']) && $_POST['ws']['firstname']!="")?$_POST['ws']['firstname']:'';
$_POST['ws']['prevname'] = (isset($_POST['ws']['prevname']) && $_POST['ws']['prevname']!="")?$_POST['ws']['prevname']:'';

echo $_POST['ws'];
  }
?>

In the above code the echo returns an array.

How do I get the same array format as $_POST['ws'] on submit of the below form. That is I want to get all the form fields in an array on submit.

 <form name="frm_passport" id="frm_passport" action="" method="POST">
  <input name="surname" id="surname" type="text" />
  <input name="firstname" id="firstname" type="text"/> 
  <input name="prevname" id="prevname" type="text"/>
  <input type="submit" name="Submit" value="Submit" id="Submit" />
</form>

I am not much aware of arrays. I am a fresher in PHP. Please anyone help me out. Thanks in advance

Upvotes: 1

Views: 91

Answers (1)

phpchap
phpchap

Reputation: 382

You'll need to change the name of your input fields as below

<form name="frm_passport" id="frm_passport" action="" method="POST">
    <input name="ws[surname]" id="surname" type="text" />
    <input name="ws[firstname]" id="firstname" type="text"/> 
    <input name="ws[prevname]" id="prevname" type="text"/>
    <input type="submit" name="Submit" value="Submit" id="Submit" />
</form>

Upvotes: 1

Related Questions