-1

I'm processing a form that submits to my PHP page. The request data looks like this:

Array
(
[submission_id] => 363112875894117228
[name] => Array
    (
        [0] => Tom
        [1] => Jones
    )

[address] => Array
    (
        [0] => 21 Jump St
        [1] => 
        [2] => Sydney
        [3] => NSW
        [4] => 2000
        [5] => Australia
    )

[cellularnumber] => Array
    (
        [0] => (041) 234-5678
    )

)

I'm trying to set a variable that contains the value of the first name, last name etc. For example I would like to set a variable:

$firstName

that is equal to Tom.

I'm familiar with using this syntax:

$firstName = $_POST['name']

but not sure how to handle the array in this case?

user982124
  • 4,416
  • 16
  • 65
  • 140

4 Answers4

0

use array index for name like

$fname = $_POST['name'][0]; $lname = $_POST['name'][1];

and use implode statement for the address like

implode(" ",$_POST['address']) (it will convert your address array to string)

Divyank
  • 740
  • 3
  • 20
0

Have you tried like this , I hope this should work for you.

$firstName = $_POST['name'][0];
$lastName = $_POST['name'][1];
Gaya
  • 32
  • 3
0

Its a multidimensional array. In your case the array element name have one more sub array. You can access it as follows,

$firstName = $_POST['name'][0];
$lastName = $_POST['name'][1];
Rajeesh
  • 23
  • 3
0

You can convert the whole array to JSON to POST using json_encode, then use json_decode to fetch all data at backend.

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/function.json-decode.php

$result = json_encode(Array
(
'submission_id' => 363112875894117228,
'name' => Array
    (
        0 => 'Tom',
        1 => 'Jones',
    ),
'address' => Array
    (
        0 => '21 Jump St',
        1 => '',
        2 => 'Sydney',
        3 => 'NSW',
        4 => '2000',
        5 => 'Australia',
    ),
'cellularnumber' => Array
    (
        0 => '(041) 234-5678',
    ),
))

End up to {"submission_id":363112875894117228,"name":["Tom","Jones"],"address":["21 Jump St","","Sydney","NSW","2000","Australia"],"cellularnumber":["(041) 234-5678"]}

Chris Chen
  • 1,228
  • 9
  • 14