7

$bookA = "123"; $crack = "A";

I want to do something similar to this:

echo $book$crack;

Such that the output is 123.

What is the correct syntax for the echo command?

Thanks.

RC.
  • 131
  • 1
  • 1
  • 5

6 Answers6

16
echo ${"book" . $crack};
Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
5

These are called variable variables, but you should use arrays instead.

Progman
  • 16,827
  • 6
  • 33
  • 48
  • 2
    Why do you say he should use arrays, when we did not explain why he needs to do it this way. Maybe the data is coming from the source he has no control of. Arrays are completely irrelevant to the question. – Milan Babuškov Apr 03 '10 at 16:40
  • Because arrays have more features (such as being easy to iterate over) and are much more readable in code. – Quentin Apr 03 '10 at 16:43
  • 2
    "Maybe the data is coming from the source he has no control of." - because evaluating the 3rd party data is terrible practice. 3rd party data should never interact with real names of variables/functions/whatever - the only possible way to interaction is to work with data. – zerkms Apr 03 '10 at 16:47
4
$varname = 'book'.$crack;
echo $$varname;
Milan Babuškov
  • 59,775
  • 49
  • 126
  • 179
4

You might want to use an associative array.

For instance:

$book = array();
$book["A"] = "Some Book";
$crack = "A";

//Later
echo $book[$crack];
Joshua Rodgers
  • 5,317
  • 2
  • 31
  • 29
2

This will work:

$bookA = "123";
$crack = "A";
$var = "book$crack";
echo $$var;
Josh
  • 10,961
  • 11
  • 65
  • 108
-1

Try the following:

echo ${book.$crack};

It works for me.

julianfperez
  • 1,726
  • 5
  • 38
  • 69