user3542456
user3542456

Reputation:

How do I get multiple values from one input field in php?

I have a form that has draggable elements that are dropped into a hidden input field. I have a php script that gets the values and adds them to an array, which is then added to a database. I then echo the contents of the array and the array length. At least that's what it's supposed to do. However, the array_push function is acting more like array_pop in that it's returning the last element added to the array and keeping the count at 1. How would I go about looping through and finding each input value? Sorry if the question title is vague.

HTML

<input type='hidden' name='findCat[]' id='findCat' value='" +cat.toUpperCase()+ "' />

PHP

if($_POST['submit'] == TRUE){
    $findCat = $_POST['findCat'];
    $emerg_array = array($findCat);
    $arrayLength = count($emerg_array);

    for($i = 0; $i < $arrayLength; $i++){
        echo $emerg_array[$i] .'<br>';
    }
    echo $arrayLength;
}

OUTPUT

Array

1

Regardless of how many elements are in the array.

Upvotes: 0

Views: 17241

Answers (2)

James
James

Reputation: 22237

Here's a simplified example that works:

<?php
if (!isset($_POST['sub'])) {
    echo "<html><body>
    <form method='post'>
        <input type='hidden' name='findCat[]' value='1'>
        <input type='hidden' name='findCat[]' value='2'>
        <input type='hidden' name='findCat[]' value='3'>
        <input type='submit' name='sub' value='submit'>
    </form>
    </body></html>";
} else {
    $findCat = $_POST['findCat'];
    var_dump($findCat); // displays array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" } 
}
?>

Could it be that your secure function is mangling the array?

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35337

You can create an array with any form element easily by adding [] to the name.

<input type='hidden' name='array[]' value='1234'>
<input type='hidden' name='array[]' value='5678'>

$_POST['array'] will contain 1234,5678.

Upvotes: 1

Related Questions