DCJones DCJones - 8 months ago 47
PHP Question

PHP array, substitut the key within a foreach loop

After reading a lot of post and not beenable to find a solution to my issue.

I have a $_POST array named "Water", $_POST['Water'] and its content is:

[Water] => Array ( [0] => 55.0 [1] => 22 )

Is it possible to use the name of the post inside a foreach loop so the $key could use the name "Water":

foreach($_POST['Water'] as $key => $val) {
$fields[] = "$field = '$val'";
//echo "Key: $key, Value: $val<br/>\n";

Many thanks for your time.


Not really. foreach() operates on the contents of an array. Whatever actually contains that array is outside of foreach's view. If you want to dynamically use the Water key elsewhere, you'll have to do that yourself:

$key = 'Water'
foreach($_POST[$key] as $val) {
   $fields[] = "$key = '$val'";