DCJones
DCJones

Reputation: 3451

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 $_POST array named "Water", $_POST['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 $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.

Upvotes: 0

Views: 58

Answers (2)

If I read this right you basically want $field='water' inside the foreach. This can be done be rethinking the way we build the foreach.

You simply need to make the field value a variable and pass use that rather everywhere the value is needed.

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

The advantage of this approach is that if you change your mind and the $_POST key is later called, "liquid" one single line needs to be edited and that is all. Furthermore, if your foreach were part of a function $field could be a function parameter. In a roundabout way, you are actually getting pretty close to some code reuse principles.

Upvotes: 0

Marc B
Marc B

Reputation: 360602

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'";
}

Upvotes: 2

Related Questions