Junaid Farooq
Junaid Farooq

Reputation: 359

Taking Form Input Tag as Array

I was trying to get Input form values in array and named all the input(text) tags as Val[] am getting it after Isset submition but it is just echoing only the first letter of each Input Value Html.

<form action="index.php" method="post">
            <input type="text" name="val[]" value="">
            <input type="text" name="val[]" value="">
            <input type="text" name="val[]" value="">
            <input type="text" name="val[]" value="">
            <input type="text" name="val[]" value="">
            <input type="text" name="val[]" value="">
            <input type="submit" name="submit" value="Submit">
</form>

PHP

if(isset($_POST['submit'])){
                $varb = $_POST['val'];
                foreach($varb as $vals){
                echo $vals['val'];
                }
}

i actually don't know how to handle Array through Input fields

Upvotes: 0

Views: 303

Answers (3)

TiMESPLiNTER
TiMESPLiNTER

Reputation: 5889

What you actually get in PHP with your HTML form markup is an array like

array(
    [0] => first value
    [1] => second value
)

So you can access an array element of it like this

$array = $_POST['val'];
echo $array[0]; // Value of first input field

Or if you like to iterate over all the entries:

$array = $_POST['val'];

foreach($array as $val){
    echo $val;
}

If you would like to access the value as you have done it in your initial PHP snippet you have to modify the name attribute of the input fileds like this

name="val[][val]"

But this makes no sense in your case, so you better adjust your PHP code.

Upvotes: 0

Tushar Gupta
Tushar Gupta

Reputation: 15923

While using for each:

On each iteration, the value of the current element is assigned and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

so $vals here in your case holds the array element, this variable to get output as :

echo $vals;

Upvotes: 0

pazzleBob
pazzleBob

Reputation: 86

Just see what you have in $_POST['val'] using var_dump($_POST['val']) and use if u don't know what in array. For your example you should use just ... echo $vals; ...

Upvotes: 1

Related Questions