1
<input type='hidden' name='var[name1]' value='1'>
<input type='hidden' name='var[name2]' value='1'>
<input type='hidden' name='var[name3]' value='1'>
<input type='hidden' name='var[name4]' value='1'>
<input type='hidden' name='var[name5]' value='1'>

Now, if I need to get all these values I can use foreach using $_POST['var'].

In some situations I need to get only some of these inputs say, 'name2' and 'name5' and $_POST['var[name2]'] and $_POST['var[name5]'] will not work.

What logic can be used in this scenario?

1
  • 1
    You know you can foreach $_POST['var']. Why not print_r() that variable and see its contents for yourself? Commented Apr 2, 2014 at 6:38

6 Answers 6

3

PHP has a special-handling for square-brackets in postvar names: it converts them into an associative-array for you.

You can access them like so:

$name1 = $_POST['var']['name1']

See the comments on the documentation on php.net: http://www.php.net/manual/en/reserved.variables.post.php

Sign up to request clarification or add additional context in comments.

1 Comment

You forgot See here section
3

since $_POST is an array and $_POST['var'] is another array you have to access it this way:

$_POST['var']['name1']

Comments

2

The variables will be converted to an array if you use square brackets, so get them this way:

$_POST['var']['name2']
$_POST['var']['name5']

Comments

1

You print the $_POST you will see this array.

    Array
(
    [var] => Array
        (
            [name1] => 1
            [name2] => 1
            [name3] => 1
            [name4] => 1
            [name5] => 1
        )

)

echo $_POST['var']['name2'];
echo $_POST['var']['name5'];

Comments

1

Try this -

echo 'Value1 = '.$_POST["var"]["name1"];
echo 'Value2 = '.$_POST["var"]["name2"];
echo 'Value3 = '.$_POST["var"]["name3"];
echo 'Value4 = '.$_POST["var"]["name4"];
echo 'Value5 = '.$_POST["var"]["name5"];

Comments

0

When you do that way, the structure becomes:

array (
  'var' => 
    array (
      'name1' => '1' 
      'name2' => '2'
      'name3' => '3' 
      'name4' => '4' 
      'name5' => '5'
   )
)

So $_POST is an array with inner array var consisting of multiple associative indexes. So you need to access it as $_POST['val']['name1']

To get all the var values at once, you can loop it like:

foreach($_POST['var'] as $val)
{
  echo $val;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.