Alex
Alex

Reputation: 68438

Array $_POST without using multiple input fields

I was wondering if it's possible to receive arrays in $_POST but with a single input field in the html and without sending the form with ajax?

Normally I would do this

<input type="hidden" name="array[]" />
<input type="hidden" name="array[]" />
<input type="hidden" name="array[]" />
.............

I was thinking of something like this

<input type="array" name="array" value="1,2,3,4" / >

Upvotes: 0

Views: 131

Answers (4)

Nahid Bin Azhar
Nahid Bin Azhar

Reputation: 763

HTML does not support array, so all the value of HTML input field is a plain text. so at first you have to explode the value of array field

$arrayOfInputs = explode(',', $_GET['array']);

and use them

echo $arrayOfInputs[0];
echo $arrayOfInputs[1];
echo $arrayOfInputs[2];

Hope you will understand

Upvotes: 0

Mohamed Ramzy Helmy
Mohamed Ramzy Helmy

Reputation: 269

You can use index notation

$_POST['array1'][0] //first element in the array
$_POST['array1'][1] // the second
$_POST['array1'][2] // the third

or you can use loop

for ($i = 0, $l = count($_POST['array1']); $i < $l; $i++) {
    doStuff($_POST['array1'][$i]);
}

Upvotes: 0

Brad
Brad

Reputation: 163334

You must have multiple input fields to submit in the normal way. However, you can generate those with JavaScript.

Add an on-submit handler to the form, and then have JavaScript append the necessary input elements to the form right before submission.

I'd provide sample code, but you didn't specify how that array would be built.

Upvotes: 0

George Cummins
George Cummins

Reputation: 28906

No, you will need to explode() the value to get an array:

$arrayOfInputs = explode(',', $_GET['array']);

Upvotes: 1

Related Questions