Home > Back-end >  How to visit an array indexed by indexed in php / Laravel?
How to visit an array indexed by indexed in php / Laravel?

Time:02-08

I got an API response like

["[email protected]","[email protected]","[email protected]"]

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?

CodePudding user response:

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();
}
  •  Tags:  
  • Related