1

why map it's not returning or pushing a values into array i tried to use use function to call my array Emails but its not working here is my logic code

   $emails = []; //emails array

    $students = User::where('role','student')->get();   //10 students email

    $maps = collect($students)->pluck('email'); //collect 10 students email

    $maps->map(function($map) use($emails){
        return  array_push($emails, $map); //push 10 students email to emails array
    });

    return $emails; //test emails array

it is returning empty email array i don't know why its not working

Ray Paras
  • 185
  • 11
  • 2
    Try with `use(&$emails)`, otherwise a basic `foreach($maps as $email) { array_push($emails, $email); }` might work better. – Tim Lewis Jan 10 '23 at 18:16
  • Or, ditch _all_ of that, and just do `return collect($students)->pluck('email')->toArray();` – Tim Lewis Jan 10 '23 at 18:17
  • &emails i used this now its working fine now thank you, kind a weird that adding & – Ray Paras Jan 10 '23 at 18:18
  • Yeah, adding `&` is [Passing by Reference](https://www.php.net/manual/en/language.references.pass.php). It means you can modify the variable inside of the function without having to return/reassign it (in a nutshell; there's a lot more happening behind the scenes with that) – Tim Lewis Jan 10 '23 at 18:19
  • thanks for the info.. first time to encounter that " & " – Ray Paras Jan 10 '23 at 18:20
  • No problem! First time I saw it I'm pretty sure I said "what the ..." too Cheers, and happy coding! – Tim Lewis Jan 10 '23 at 18:22
  • @RayParas be careful when accepting or using ChatGPT generated answers. There's no way a normal user can post 8 long answers in 30 minutes. ChatGPT answers look well written but the actual technical details can be completely wrong. – Panagiotis Kanavos Jan 10 '23 at 18:58

0 Answers0