1

I'm having some trouble with writing some syntax. I want to echo this

'location_1' => $location_1,

However, it is not as simple as it seems. When I write the echo statement the integer 1 must be the variable $z. Here is the code I attempted to write

echo "'location_' . $z . '' =>' . ${'location_' . $z} . ','";

This is what it outputted

'location_' . 1 . '' =>' . something . ','

$location_1 is equal to the string something. I'm lost at how to do this the right way. Any guides on describing how this syntax works would be a major help too so I can understand it completely.

5 Answers 5

2

You can just write variables directly into double quoted strings see http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

echo "'location_$z' => \$location_$z,";

You might want to also read the rest of the strings doc

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

Comments

1

This is the link to the echo documentation (see the examples, I think they described well how it works)

Comments

1

You can break it into two lines and get the expected output.

For example:

$var_location = "$". "location". $z;

echo "'location_" . $z . "' =>'" . $var_location . "','";

Comments

1

One way is: echo "'location_{$z}' => \$location_{$z},";

Edit: Is this what you meant?

<?php
$z = 1;
$location_1 = 'something';
echo "'location_$z' => " . ${'location_'. $z} . ',';

which produces: 'location_1' => something,

Why don't you store these variables inside an array for easier access. Something like:

$locations = array('location_id' => 'location_name');

Comments

1

Here's one way:

echo "'location_$z' => \$location_$z,";

You need to escape the $ symbol. The double quotes represent the thing to echo in this case, whereas the single quotes actually get echoed.

Comments

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.