To define a variable name to use, from another variable value

This is something that I think should be simple, but I can’t think of a way to do it.
I have a list of variables defined as strings in an include file. They are named with the prefix ‘str’, so as not to start with a number, followed by 4 digits, which define a date (mmdd), for exaple: $str0924 for the 24th of Sept.
I want the string inserting into another string, but the date is not always the same.
I have $day defined as the required 4 digits. How do I call the required string using $day?

$MyString = 'Foo' ;
$MyString .= $str#### ; // #### is the value of $day
$MyString .= 'Bar' ;

Any ideas?

$MyString .= ${"str" . $day};

if the word of StackOverflow is anything to go by.

2 Likes

That works, thank you.
I thought it must be something simple like that.
BTW, as you may have guessed, this is an alternative method to the problem in my other post (using eval), which I have not got working. I did have each date as a file (09-24.php) to call up.
But with this method I will have one file for all dates.
I know I could use a database for this, but I find php files easier to edit.
I will probably go with this method, since I have it working now.

Alternatively you could use

$var = 'str'.$day;
$MyString = $$var;

or

$var = "str$day";
$MyString = $$var;

or even

$var = "str{$day}";
$MyString = $$var;

Option 2 is the worst, because it’s quite unreadable, option 3 is a bit better, but for short stuff like this I prefer option 1. That’s personal of course, YMMV :slight_smile:

Interesting to see there are a number of options on how to do this. Thanks for the info, my script works now.