Skip to content
Advertisement

Multiple values for PHP array key

I have a rather simple script which uses a hardcoded array to load employees and their names and emails, then loops through each array element and sets an email address array so that it emails each report to the right person.

The issue is that each employee will have multiple emails, so I need to have the email key consume multiple addresses and then when I loop below it would need to email that report to multiple people

What’s the best way to alter this?

        $items = array(
        array(
         "employee" => 5273,
         "name" => "Jon Doe",
         "email" => "emp1@newSite.com"
        ),
        array(
         "employee" => 5274,
         "name" => "Jane Doe",
         "email" => "emp2@newSite.com"
        ),
        
    );

    foreach($items as $item){
        
        $dealerNum = $item["employee"];
        $dealerName = $item["name"];

        $emails = config('emails.employees');
        if (array_key_exists('email',$item)){ 
                $emails['to'][] = $item['email'];  
        }
    }

Advertisement

Answer

Make the email value an array. Then you can append it to $emails['to'].

There’s no need to call config('emails.employees') every time through the loop. Call it once before the loop, then add to the emails inside the loop.

$items = array(
    array(
        "employee" => 5273,
        "name" => "Jon Doe",
        "email" => ["emp1@newSite.com"]
        ),
    array(
        "employee" => 5274,
        "name" => "Jane Doe",
        "email" => ["emp2@newSite.com", "emp3@newSite.com"]
        ),
        
    );

$emails = config('emails.employees');
foreach($items as $item){
        
    $dealerNum = $item["employee"];
    $dealerName = $item["name"];

    if (array_key_exists('email',$item)){ 
        $emails['to'] += $item['email'];
    }
    $emails['to'] = array_unique($emails['to']); // remove duplicates
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement