0

I have arrays with the following names: $MyMondayClasses, $MyTuesdayClasses, $MyWednesdayClasses, $MyThursdayClasses, $MyFridayClasses

And I have an array for days of the week: $days = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday');

I want to loop through the days of the week and then run the appropriate array, but I'm not sure how to refer to the variable to make:

foreach($days as $value){
    foreach($My{$value}Classes as $ClassKey => $ClassVar){
        some code goes here
    }
}

I used to use eval for this sort of thing, but understand that's not best practice. Anyway, the above code isn't working.

2
  • 1
    Why don't you just have one class that you pass the day of the week to? I presume the days of the week classes will be similar. Commented Mar 20, 2013 at 16:25
  • 1
    have you considered constructing your $MyDAYClasses arrays in another array with the days for indices from the beginning ? e.g. classes = array('Monday'=> $MyMondayClasses), ...); That way when you want to look them up, you can find them easily. Commented Mar 20, 2013 at 16:29

2 Answers 2

2

I have arrays with the following names: $MyMondayClasses, $MyTuesdayClasses, $MyWednesdayClasses, $MyThursdayClasses, $MyFridayClasses

Sounds not very clever.

Why don’t you just have one array, with 'monday', 'tuesday' etc. as keys - and then have your data arrays for each day under that key …?

1
  • Sounds not very clever sounds very not-clever. I done gone made a grammatical mistake up :-P (+1) Commented Mar 20, 2013 at 16:34
0

Does not make sense .. you should use array but if you insist you can try :

foreach ( $days as $value ) {
    $name = sprintf("My%sClasses", $value);
    if (! isset(${$name})) { // the boss asked
        continue;
    }
    foreach ( ${$name} as $ClassKey => $ClassVar ) {
        // play some ball
    }
}
0

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.