PHP: New variable from string concatenated with variable (variable-variables)

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

  •  02-04-2022
  •  | 
  •  

سؤال

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?

هل كانت مفيدة؟

المحلول

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

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

نصائح أخرى

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};
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top