Use input value as an array variable

I’m totally new to php. I’m trying to echo the value of an input field into a an array but it doesn’t seem to work.e.g echo the value of hidden-input as the value for origin in the array. How can I achieve this.

<form method="post">

<input id="hidden-input" from="from[]" value="">



    $params = array(
        'origin'        =>  $_POST['from'],
        'destination'   => um_user('postal_zip_code'),
        'sensor'        => 'true',
        'units'         => 'imperial'
    ); ?>

You need to name it:

<input id="hidden-input" name="from[]" value="from person 1">
<input id="hidden-input" name="from[]" value="from person 2">

You will then find that $_POST['from'] is an array of both from person 1 and from person 2.

I assume that’s what you’re looking for?

It still doesn’t work.

You have brackets in input name:

<input id="hidden-input" from="from[]" value="">

As Anthnee said, that makes $_POST[‘from’] an array. In your case, it will be array with one element (as you have one input). So, to get value from that array you should specify an element index:

echo $_POST['from'][0];

Echo can’t work as shown below. It didn’t work.

'origin'        =>  echo $_POST['from'][0],

Of course it didn’t. I used echo only as example. You don’t need it if you’re making an assignment.

'origin'        =>  $_POST['from'][0],

Also I didn’t get what are you trying to achieve actually?

Do you want $params['origin'] to be an array (contain multiple values)?
If so, code in your OP should work.

Or do you want $params['origin'] to contain value from single input?
If yes, then there is no need to use brackets in input name

Yes I want $params['origin'] to contain value from single input. I inserted the input value with jQ and I want the users to see the distance from them to the users calculated automatically. It works if I add the value automatically.

Then you don’t need [] in input name:

<input id="hidden-input" from="from" value="">

Accordingly, no need to specify additional array index for $_POST[‘from’] as well:

'origin' =>  $_POST['from'],

Brackets in input names are used only when it is necessary to have two or more inputs with the same name but different values (see example in post #2).

Are you ever actually posting the data? If there’s no submit then it will never show up:

<form action="post">
    <input type="hidden" name="from" value="Foo">
    <input type="submit" value="Post data">

if (isset($_POST['from'])) {
} else {
    echo "You need to submit the form to see the POST data";

Something like that

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.