1
\$\begingroup\$

I am using PHP, and I am getting the value back from the form. Since I am working with time, I have an array by (1 x 4) x 7, and I feel like I could do a better job at it. I just don't know exactly how should I approach the problem

$schedule = array(
    round(abs(strtotime($_POST['mon'][1]) - strtotime($_POST['mon'][0])) / 3600, 2),
    round(abs(strtotime($_POST['mon'][3]) - strtotime($_POST['mon'][2])) / 3600, 2),

    round(abs(strtotime($_POST['tue'][1]) - strtotime($_POST['tue'][0])) / 3600, 2),
    round(abs(strtotime($_POST['tue'][3]) - strtotime($_POST['tue'][2])) / 3600, 2),

    round(abs(strtotime($_POST['wed'][1]) - strtotime($_POST['wed'][0])) / 3600, 2),
    round(abs(strtotime($_POST['wed'][3]) - strtotime($_POST['wed'][2])) / 3600, 2),

    round(abs(strtotime($_POST['thu'][1]) - strtotime($_POST['thu'][0])) / 3600, 2),
    round(abs(strtotime($_POST['thu'][3]) - strtotime($_POST['thu'][2])) / 3600, 2),

    round(abs(strtotime($_POST['fri'][1]) - strtotime($_POST['fri'][0])) / 3600, 2),
    round(abs(strtotime($_POST['fri'][3]) - strtotime($_POST['fri'][2])) / 3600, 2),

    round(abs(strtotime($_POST['sat'][1]) - strtotime($_POST['sat'][0])) / 3600, 2),
    round(abs(strtotime($_POST['sat'][3]) - strtotime($_POST['sat'][2])) / 3600, 2),

    round(abs(strtotime($_POST['sun'][1]) - strtotime($_POST['sun'][0])) / 3600, 2),
    round(abs(strtotime($_POST['sun'][3]) - strtotime($_POST['sun'][2])) / 3600, 2),
);
\$\endgroup\$

closed as off-topic by Toby Speight, Sᴀᴍ Onᴇᴌᴀ, Hosch250, Gerrit0, VisualMelon Jan 12 at 20:32

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – Toby Speight, Sᴀᴍ Onᴇᴌᴀ, Gerrit0, VisualMelon
If this question can be reworded to fit the rules in the help center, please edit the question.

2
\$\begingroup\$

Well, every time you see a repeated code, you could think of a loop.

if I am not mistaken, only a weekday is changed, so it could be used to form the loop:

$schedule = [];
$weekdays = ['mon','tue','wed','thu','fri','sat','sun'];
foreach ($weekdays as $day)
{
    $schedule[] = round(abs(strtotime($_POST[$day][1]) - strtotime($_POST[$day][0])) / 3600, 2),
    $schedule[] = round(abs(strtotime($_POST[$day][3]) - strtotime($_POST[$day][2])) / 3600, 2),
}
\$\endgroup\$
  • \$\begingroup\$ Thank you. Managed to remove a lot of code that were similar by at least 40%! \$\endgroup\$ – user93905 Jan 16 at 18:12

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