PHP Puzzler: finding the value of a variable's variable when the variable's value includes a slash

StackOverflow https://stackoverflow.com/questions/23577434

Question

I've been puzzling over this for quite some time, and I'm hoping someone has an idea. Here's the code:

<?php
$Trucking_CPA="25.00"; // set price
$Trucking_price="\$Trucking_CPA"; // I know, that slash is the problem - but I need it there for other purposes in the program.

echo $Trucking_CPA."<br />"; // prints $25.00 - that's fine and expected

echo $Trucking_price."<br />"; // prints $Trucking_CPA (with no slash for some reason...)

echo $$Trucking_price."<br />"; // With double $ - Gives error: Notice: Undefined variable: $Trucking_CPA - why?

$anothertry1 = ${$Trucking_price};

echo $anothertry1."<br />"; // With double $ in brackets - Gives error: Notice: Undefined variable: $Trucking_CPA - why?

$anothertry2 = ${stripslashes($Trucking_price)};

echo $anothertry2."<br />"; // With double $ in brackets and stripslashes - Gives error: Notice: Undefined variable: $Trucking_CPA - why?

 ?>

I need to have that slash there so it's not converted elsewhere, because the logic is checking it and it can't be equal to the variable's value in that case.

Anyone have an idea how I can get PHP to give me the 25.00 by calling $Trucking_price?

Update - this question was excellently answered below, so just to re-cap for future users running into this:

<?php
$Trucking_CPA="25.00"; // set price
$Trucking_price="\$Trucking_CPA";
echo ${substr($Trucking_price,1)}; // returns 25.00 instead of $Trucking_CPA
 ?>
Was it helpful?

Solution

You can try the following :

echo ${substr($Trucking_price,1)};

It will cut $ from the string $Trucking_price and return Trucking_CPA.After that you can call this variable like ${'Trucking_CPA'}.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top