PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 22, 2022

[FIXED] PHP doesn't replace variables with defined values in a String

 January 22, 2022     php     No comments   

Issue


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?


Solution

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.



Answered By - bobkorinek
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing