0

I have an array of 4 email addresses. Every Tuesday I need to send out an email, so I use CRON to run a php script. The script contains an array of email addresses. Week 1 I send an email to array[0], week 2 I send an email to array[1], week 3 I send an email to array[2] and week 4 I send an email to array[3]. Then I repeat, so week 5 I send an email to array[0], and so on into infinity.

How do I do the math on date() to figure out which email to send when the script runs? The only thing I can think to do is to fill out a date lookup array for the next 10 years after a start date, then do a lookup but that seems inefficient.

Bonus points if next year, I could add another user to the array without upsetting the order to date.

John Vargo
  • 530
  • 3
  • 9

2 Answers2

1

You can use some modular math operation to implement a simple round robin system.

Also, you can get the week number using date("W")

Assuming you only have 3 arrays:

<?php
$emails = [
    ['email1@corp.com', 'email2@corp.com', 'email3@corp.com'],
    ['email1@anothercorp.com', 'email2@anothercorp.com', 'email3@anothercorp.com'],
    ['email1@athirdcorp.com', 'email2@athirdcorp.com', 'email3@athirdcorp.com'],
];
$roundRobinSize = count($emails);
$thisWeekEmailsList = $emails[(intval(date("W")) - 1) % $roundRobinSize];
someFunctionForSendingMail($thisWeekEmailsList, 'Subject', 'Message');

This code can get the wrong array if eventually you add another list. That's because it's implemented a simple round robin based on the week number.

William Okano
  • 370
  • 1
  • 3
  • 10
1

If I understand correctly, you don't have a problem in when to send but to whom, adhering to a certain order. That said, aren't you looking for a solution in the wrong area?

Why not simply store the index number of the array somewhere (e.g. in a plain file) of whom you have sent the email? And automatically updating that file when the cron is executed (each Tuesday)? This allows you to add another user without upsetting the order.

See example code below:

// The list with users
$userList = [
  0 => "you@domain.tld",
  1 => "john.doe@domain.tld"
];

// Determine the user who received last email
$lastUsedIndex = 1; // e.g. extract this input from a file

// Determine the last user in the list
$maxUserIndex = max(0, count($userList) - 1);

// Determine who is next in line to receive the email
$newIndex = (++$lastUsedIndex <= $maxUserIndex ? $lastUsedIndex : 0);
$reciever = $userList[$newIndex];

// Send the email

// Update the source containing the last receiver (which is the value of $newIndex)