I get a different scope for the variable inside the condition in PHP – how to fix it?

There are fields in My e-commerce which values come from the form $ _POST, including billing_email1, billing_email2, billing_email3, etc. depending on the given amount. (there are other fields too, but we are not interested here)

My task is to write incoming values to the fields:
In billing_email, the first value is billing_email1, and in billing_email_dop, all subsequent billing_email2, billing_email3, etc. through a semicolon.

I’ve been fighting for weeks, I just can’t figure out what the reason why the $ key outside and inside conditions turn out to be different:
get_checkout_fields( 'billing' );

foreach ( $fields as $key => $field ) {
$i = 1;
$postdata = "";
$postdop = "";
$postemail = "";
var_dump($key); // $key = billing_email_dop
if($_POST["$key"."$i"]) {
var_dump($key); // $key = billing_email_dop $key = billing_email
while($_POST["$key"."$i"]) {

if($key==="billing_email") {
if(("$key"."$i")=="billing_email1") {
$postemail = $_POST['billing_email1'];
else {
$postdop .= $_POST["$key"."$i"]."; "; //в $postdop
else {
$postdata .= $_POST["$key"."$i"]."; ";
if($key=="billing_email") {
woocommerce_form_field( $key, $field, $postemail );
else if($key=="billing_emaildop") {
woocommerce_form_field( $key, $field, $postdop );
else {
woocommerce_form_field( $key, $field, $postdata );

Advanced Web Care Professional Web Development

You can make var_dump $ fields after $ checkout-> get_checkout_fields ('billing'); but it is not clear what you get there, maybe it is generally a resource ...
PS: add if ($ _ POST ["$ key". "$ I"]) {...} else {var_dump ($ key);} and everything will fall into place.

PPS: in general, you code is not good, and it replete with both obvious errors and implicit glitches (for beginners) ... for example, billing_email_dop eventually becomes billing_emaildop; etc. A classic example of how to do NOT.

How to make your code better:
1) It makes no sense to build a cycle on $ fields, you clearly know its structure, unlike the data from $ _POST.

2) In the $ _POST loop, look for matching keys (for example, checking for a billing_email substring or a regular expression for billing_email \ d {1,2}). If exactly billing_email1 - write to $ postemail, otherwise $ postdop [] = $ val; The form fields should be called more clearly, for example, billing_email [], after which you can immediately get the whole array of emails.

3) Additionally, if $ postdop is not empty, use a comma to impart the values of $ postdop, get your comma-separated email line.

4) assign all the required fields of your $ fields.

5) Enjoy