I want to tell my function which variable to call based on the day of the week. The day of the week is stored in $s_day, and the variables I want to call changes based on which day it is.

e.g.

I've stored a string 'Welcome to the week' in $d_monday_text1. Rather than build a set of 7 conditional statements (e.g. if date=monday echo $foo, else if date=tuesday echo $bar...), can I change the name of the variable called in the function by concatenating the name of the variable?

$s_day = date("l");
$text1 = '$d_'.$s_day.'_text1';

I'm hoping this evaluates to $d_monday_text1, which, as mentioned above, has the value "Welcome to the week". So, later on I'd want to use:

echo $text1;

To yield the resulting output = Welcome to the week.

I've looked into variable variables, which may be the way to go here, but am struggling with syntax. I can get it to echo the concatenated name, but I can't figure out how to get that name evaluated.

share|improve this question
possible duplicate of Can I use a generated variable name in PHP? – outis Oct 1 '10 at 4:04
feedback

2 Answers

up vote 8 down vote accepted

Variable variables aren't a good idea - You should rather use arrays. They suit this problem much, much better.

For example, you could use something like this:

$messages = array(
    'monday' => 'Welcome to the week',
    'tuesday' => 'Blah blah',
    'wednesday' => 'wed',
    'thursday' => 'thu',
    'friday' => 'fri',
    'saturday' => 'sat',
    'sunday' => 'week is over!'
);

$dayName = date('l');
echo $messages[$dayName];

Arrays are the data format used to store multiple related values such as these.

share|improve this answer
Thanks Jani. I think this would work for a smaller dataset than I have. It does fit the example given, which is a simplified explanation of what I'm doing here. – jkramp Nov 30 '09 at 5:17
In general I think arrays should be used whenever you have a dataset of any size. Using dynamic naming for variables is generally a poor idea, as it does not give the data any structure and it makes the code less readable. – Jani Hartikainen Nov 30 '09 at 5:22
Okay, let me noodle on it a bit more and I'll update the question to see if there's a better way to go using arrays. Probably due to the way my data is structured it is easier to use the dynamic expression than the array. that's not to say my data structure isn't flawed. – jkramp Nov 30 '09 at 5:31
feedback

You can use this syntax:

$$text1

I've used this before. The evaluation comes as in:

$($text1)

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.