Hi, Help please:
I'm new to PHP, and I've been struggling with this 'simple' problem:

This is a simple example of my problem:
The variable name: $data_01 / needs to be made up dynamically.

The variable: $file_name / needs to return the value of variable: $data_01
...but instead, it returns the constructed variable name: $data_01

I've tried many permutations, using variables & arrays, and I cant get it to work, so what am I missing?

$data_01 = "I need to RETURN this text";

$file_name_prefix = '$data_';
$file_name_suffix = "01";
$file_name = "$file_name_prefix$file_name_suffix";

echo ("Result 1: $file_name_prefix$file_name_suffix");
echo ("<br>");
echo ("Result 2: $file_name");

Many thanks

    Your example is showing two different things, a variable holding a string and producing filenames, so, you need a better example for us to really know what you are trying to accomplish.

    If you do have variables named $data_01, $data_02, ..., stop and change the design to use an array. For accessing a particular string among several defined choices, the variable needs to be an array, with the array index being the 1,2,3,... You would access the array using -

    $data[1] = 'I need to RETURN this text';
    $data[2] = 'Some other text';
    
    $index = 1; // get/set an index for the array element you want to access
    echo $data[$index];
    

    If you are instead trying to reference a filename composed of a prefix and numerical suffix, the value (not the variable name) you are tying to produce would be made up of those two things concatenated together and if the prefix is in a variable already, just use that variable, don't make up more variables.

      I strongly recommend using an array/hash for this, as mentioned above, but PHP does support variable variables if you really need it:

      11:54 $ php -a
      Interactive shell
      
      php > $foo = 'fu';
      php > $bar = 'bar';
      php > ${$foo.$bar} = $foo.$bar;
      php > echo $foobar;
      fubar
      php >
      
        Write a Reply...