0

I am trying to keep my page a pure template, so i never have to change the markup page. layout is in templates and text is in another file. Would like to make it simple to build the markup so was hoping something like this could be done:

On page 1 holding text:

$varaudio = "audio text about stuff";

on page 2 calling for variable:

$var1="audio"

$var+var1
alwayslearning
  • 411
  • 5
  • 18
  • 1
    Well you don't use `+` for a start.... `+` is for adding two numbers together; but read the friendly manual, and it will tell you about [variable variables](http://php.net/manual/en/language.variables.variable.php) – Mark Baker Feb 13 '15 at 13:39
  • `$varaudio = "audio text about stuff"; $var1="audio" $var = 'var' . $var1; echo $$var;` – Mark Baker Feb 13 '15 at 13:41
  • possible duplicate of [Dynamic variable names in PHP](http://stackoverflow.com/questions/9257505/dynamic-variable-names-in-php) – Rizier123 Feb 13 '15 at 14:30

4 Answers4

0

Very ugly solution that works

$var = "test";
$test = "1231";
echo $$var; // prints 1231
leopik
  • 2,323
  • 2
  • 17
  • 29
0

You're looking for variable variables http://php.net/manual/en/language.variables.variable.php

$varaudio = "audio text about stuff";

$var1="audio";
echo ${'var'.$var1}

// audio text about stuff

I would try to find some other solution for this problem instead of the above. It's just kinda messy/hacky.

JimL
  • 2,501
  • 1
  • 19
  • 19
0

Assuming $var1 = "audio"; amd $varaudio = "audio text about stuff";, this code will print "audio text about stuff" :

$varname = "var" . $var1;
echo $$varname;

Note the double $$

stwalkerster
  • 1,646
  • 1
  • 20
  • 30
0

Try this one:

<?php
$varaudio = "audio text about stuff";

// make an array consist of above words
$var_array = explode(' ', $varaudio);

// for each word in $var_array make "$var_{counter}" variable that contains
// that word
for ($i=1; $i <= count($varaudio); $i++) { 
    // make variable name
    $var_name = 'var_'.$i;

    // make variable with above name
    $$var_name = $var_array[$i-1];

    // here $var_1 will be equal to audio
}

I hope this helps.

Lost Koder
  • 864
  • 13
  • 32
  • everyone is mentioning tgat there way is messy/ hacky. so i guess this is the clean option using arrays, can you explain the code a little please. – alwayslearning Feb 13 '15 at 14:21
  • No, this is just as dirty/hacky as the other ways..... it's the use of variable variables that's dirty/hack.... just because you loop an array to generate those variable variables, doesn't make them any less dirty/hacky – Mark Baker Feb 13 '15 at 14:24
  • is it possible to take if further and enter the variable into this: – alwayslearning Feb 13 '15 at 14:33
  • so use the variable name in locating the filename – alwayslearning Feb 13 '15 at 14:34