Question

I am having a basic php problem that I haven't been able to resolve and I would also like to understand WHY!

 $upperValueCB = 10;
 $passNodeMatrixSource = 'CB';

 $topValue= '$upperValue'.$passNodeMatrixSource;

 echo $topValue;

OUTPUT $upperValueCB

but I want OUTPUT as the variable's value 10.

How can I make PHP read the $dollar-phrase as a variable and not a string?

Was it helpful?

Solution

$varName = 'upperValue' . $passNodeMatrixSource;
$topValue = $$varName;

http://php.net/manual/en/language.variables.variable.php

OTHER TIPS

This little example might illustrate what you are about to do:

<?php

$a = 'b';
$b = 10;

echo ${$a}; // will output 10

So you will have to change your example to:

$upperValueCB = 10;
$passNodeMatrixSource = 'CB';

$topValue= 'upperValue'.$passNodeMatrixSource;

echo ${$topValue}; // will output 10

You can do it this way :

$upperValueCB = 10;
$passNodeMatrixSource = 'CB';

$topValue= ${'upperValue'.$passNodeMatrixSource};

echo $topValue;

Because upperValueCB is the var name, if you want PHP to understand which var to use, you have to give the var name.
For that, you can use static way like $upperValueCB
or using a string like this : ${'upperValueCB'}
or using a third var containing the var name $var = 'upperValueCB'; $$var;

 $upperValueCB = 10;
 $passNodeMatrixSource = 'CB';

 $topValue= 'upperValue'.$passNodeMatrixSource;

 echo ${$topValue};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top