Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Battle of for and foreach

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #44016
    matt_sanford
    Participant

    I am trying to keep my code efficient and not repeat myself but I am finding it a little tough. (I am sure it would be easier if I had been doing this for more than a few weeks).
    I am making a schedule using “foreach” and calling that loop three times because I each time I call a different Item out of an array. How can I do this without the extra 20 lines of code?
    Here is what I have.

    $days = array(“Friday”, “Saturday”, “Sunday”);
    $hourAm = array(6, 7, 8, 9, 10, 11);
    $hourPm = array(12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
    $locations = array(“Holiday Ballroom”, “Key Ballroom”, “Assigned Rooms”, “West Foyer”)

    function scheduleFriday() {
    GLOBAL $days, $hourAm, $hourPm;
    echo “

    $days[0]

    “;
    foreach ($hourAm as $hourA) {
    echo ‘

    ‘ . $hourA . “am” . ‘

    ‘;
    }
    foreach ($hourPm as $hourP) {
    echo ‘

    ‘ . $hourP .”pm” .’

    ‘;
    }

    unset($hourA);
    unset($hourP);
    }
    function scheduleSaturday() {
    GLOBAL $days, $hourAm, $hourPm;
    echo “

    $days[1]

    “;

    foreach ($hourAm as $hourA) {
    echo ‘

    ‘ . $hourA . “am” . ‘

    ‘;
    }

    foreach ($hourPm as $hourP) {
    echo ‘

    ‘ . $hourP .”pm” .’

    ‘;
    }

    unset($hourA);
    unset($hourP);
    }
    function scheduleSunday() {
    GLOBAL $days, $hourAm, $hourPm;
    echo “

    $days[2]

    “;

    foreach ($hourAm as $hourA) {
    echo ‘

    ‘ . $hourA . “am” . ‘

    ‘;
    }

    foreach ($hourPm as $hourP) {
    echo ‘

    ‘ . $hourP .”pm” .’

    ‘;
    }

    unset($hourA);
    unset($hourP);
    }
    ?>

    And then in my html I am calling each of those functions in their respective rows.
    Thanks!

    #131300
    CrocoDillon
    Participant

    function scheduleFriday() {
    scheduleDay(0);
    }

    function scheduleSaturday() {
    scheduleDay(1);
    }

    function scheduleSunday() {
    scheduleDay(2);
    }

    function scheduleDay($day) {
    GLOBAL $days, $hourAm, $hourPm;
    echo $days[$day];
    foreach ($hourAm as $hourA)
    echo $hourA . ‘am’;
    foreach ($hourPm as $hourP)
    echo $hourP . ‘pm’;
    }

    I think the forum ate your line feeds but you get the point :) No need to unset those variables.

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘Back End’ is closed to new topics and replies.