2

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?

9
  • 2
    $topValue = $upperValueCB . $passNodeMatrixSource;? Why the quotes? Commented Apr 6, 2013 at 14:31
  • $upperValue isn-t a variable it's a string Commented Apr 6, 2013 at 14:32
  • Ok... I guess I don't quite understand the problem then... Commented Apr 6, 2013 at 14:35
  • show the exact output you want to get Commented Apr 6, 2013 at 14:37
  • @yefrem, I said I wanted the variable-s value 10 Commented Apr 6, 2013 at 14:38

4 Answers 4

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Chosen for the link! Can you put it in the answer too!!
4

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

4 Comments

I don't think so. Have you tested it? it outputs 10 because the variable names $b or $upperValueCB will being generated dynamically
Hehe.. No problem.. Note that the syntax of @AlucardTheRipper is also correct
Cheers again, gave three plus ones but gave the correct to @alucardtheripper for the php manual link and because he only HAD 1 point AND was first correct too I think!
No problem. Also note that the syntax of his answer is shorter than my. Programmers are lazy. isn't it ? ;)
2

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;

2 Comments

Thanks +1, thought the problem was parsing '' not variable naming
Thank's for that, but I think the problem was well in the method used to call the var correctly. ;)
0
 $upperValueCB = 10;
 $passNodeMatrixSource = 'CB';

 $topValue= 'upperValue'.$passNodeMatrixSource;

 echo ${$topValue};

1 Comment

This will print "10CB" instead of "10"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.