Home > front end >  PHP doesn't replace variables with defined values in a String
PHP doesn't replace variables with defined values in a String

Time:12-31


Here is a part of my PHP application:

Stage 1:
I get an array of payment methods from user and assign an ID to it, because it can contain multiple choices.

I filled $paymentMethod variable with some examples.

$paymentMethod = ['PayPal','Visa','Master'];
$paymentMethodNames = array("PayPal", "Visa", "Master", "COD");
$paymentMethodNumerical = array("1", "2", "3", "4");
$paymentMethodCalculated = implode(str_replace($paymentMethodNames, $paymentMethodNumerical, $paymentMethod));

the result of echo $paymentMethodCalculated is 123 which is perfectly correct.

Stage 2:
I need to create a special variable which is needed to work for another part of my application.

for ($x = 0; $x < strlen($paymentMethodCalculated); $x  ) {
$paymentFinal .= '$_'.substr($paymentMethodCalculated, $x, 1);
    if(isset($paymentFinal) && $x !== strlen($paymentMethodCalculated) - 1) {
       $paymentFinal .= '.",".';
    }
}

The result of echo $paymentFinal is $_1.",".$_2.",".$_3 which is perfectly correct.

Stage 3:
Now I define:

$_1 = Test;
$_2 = Test2;
$_3 = Test3;

Now, when I echo $paymentFinal
It still shows:
$_1.",".$_2.",".$_3

But my desired result is:
Test.",".Test2.",".Test3


Question: Why PHP does not replace defined variables in $paymentFinal variable?

CodePudding user response:

The problem is that PHP doesn't alter your string based on your defined variables. You have variable, which contains set of characters which remain the same until you alter the string by yourself (like str_replace or something similar). The "variables" inside $paymentFinal ("$_1.",".$_2.",".$_3") are just set of characters; they don't represent the actual variables you have defined inside your code.

  •  Tags:  
  • php
  • Related