Skip to content
Advertisement

How to visit an array indexed by indexed in php / Laravel?

I got an API response like

["at123@gmail.com","adhd5@gmail.com","adahsad5@gmail.com"]

I got this array in a request variable $request->optional_email I am trying to access data by a loop like below:

foreach ($request->optional_email as $key => $optionalEmail) {
    $email->email = $optionalEmail[$key];
    $email->save();
}

But it doesn’t work. How can I solve it?

Advertisement

Answer

As the $request->optional_email is just a list you do not need to use the $key variable in the foreach. Instead you should just use the value ($optionalEmail) of the foreach so your code would look something like this:

foreach ($request->optional_email as $optionalEmail) {
    $email->email = $optionalEmail;
    $email->save();
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement