Grow your CSS skills. Land your dream job.

Battle of for and foreach

  • # April 10, 2013 at 1:53 pm

    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.

    < ?php
    $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!

    # April 10, 2013 at 2:33 pm

    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)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".