views:

40

answers:

3

Using PHP. I'm trying to retrieve $_POST values from a the second dimension of a two dimensional $_POST array without actually knowing the names of the values being posted. Here is what I have; it doesn't work.

foreach($_POST as $k=>$v) {

    $$k=$v;

    if (is_array($k) == true) {

        foreach($k as $value) {

            echo $value;
            echo "<br>";

        }

    }

}

I used

echo '<pre>'; 
print_r($_POST); 
echo '</pre>';

to make sure there are values in the arrays and there are. It shows:

Array
(

    [colors] => Array
        (
            [0] => red
            [1] => yellow
            [2] => blue
            [3] => black
        )

)

This is what my form check boxes look like:

<input name="colors[]" type="checkbox" value="red" />
<input name="colors[]" type="checkbox" value="yellow" />
<input name="colors[]" type="checkbox" value="blue" />
<input name="colors[]" type="checkbox" value="black" />

How do I get the values from an array within an array if I don't know the name of the array. The name won't always be colors?

+4  A: 

You're almost there. This should work:

foreach($_POST as $k=>$v) {

     if (is_array($v) == true) {

        foreach($v as $value) {

           echo htmlspecialchars($value); // Always sanitize when you output! :) 
           echo "<br>";

        }

    }

}
Unicron
+1  A: 

The simple reason why your above code does not work is because you're checking whether the array key is an array, not the actual value itself. Swap out...

if (is_array($k) == true)

with

if (is_array($v) == true)

Do the same in the nested foreach clause.

And it should work fine. Also, you might as well drop the boolean comparison, is_array returns a boolean, you're not making it any more explicit than it already is.

Denis 'Alpheus' Čahuk
A: 
foreach( $_POST as $key => $item ) {
    if ( is_array($item) ) { // you want to check if the value is an array, not the key
        foreach($item as $index => $value) {
            echo $value . "\n<br>";
        }
    }
}
nathan