DCJones DCJones - 1 year ago 83
PHP Question

PHP array, substitute the key within a foreach loop

I have read a lot of posts and have not been able to find a solution to my issue.

I have a

array named "Water",
and its contents are:

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

Is it possible to use the name of the post inside a foreach loop so the
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.

Answer Source

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'";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download