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?

0

5 Answers 5

16
echo ${"book" . $crack};
Sign up to request clarification or add additional context in comments.

Comments

6

You might want to use an associative array.

For instance:

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

//Later
echo $book[$crack];

Comments

4
$varname = 'book'.$crack;
echo $$varname;

Comments

4

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

3 Comments

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.
Because arrays have more features (such as being easy to iterate over) and are much more readable in code.
"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.
2

This will work:

$bookA = "123";
$crack = "A";
$var = "book$crack";
echo $$var;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.