Home > Enterprise >  Loop on a variable delimited with gamma using Laravel 8
Loop on a variable delimited with gamma using Laravel 8

Time:10-05

I have in my database values with this form :

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

I'm using laravel and I want to loop on this variable to get each element for example get the element : [email protected].

I tried the following code :

I have the following array :

$emails :
    array:2 [▼
      0 => "["email1@gmail.com","email2@gmail.com"]"
      1 => "["email3@gmail.com","email4@gmail.com"]"
    ]

So I'm using the following code to get each element :

$var = array();
          foreach ($emails as $key => $value) {
            $var[] = $value;
          }

I get the following result :

array:2 [▼
  0 => "["email1@gmail.com","email2@gmail.com"]"
  1 => "["email3@gmail.com","email4@gmail.com"]"
]

If you have any idea , please help

UPDATE

I have the following array :

array:2 [▼
  0 => "["email1@gmail.com","email2@gmail.com"]"
  1 => "["hajar.boualamia33@gmail.com","guernine.khadija@gmail.com"]"
]

And I did the following method :

$emailss = collect($emails)->flatten()->all();
 dd($emailss);

I get the following result :

array:2 [▼
  0 => "["email1@gmail.com","email2@gmail.com"]"
  1 => "["hajar.boualamia33@gmail.com","guernine.khadija@gmail.com"]"
]

CodePudding user response:

Update

Ha, tricky one. It seems that you have a PHP expression (an array) stored. So in order to extract the arrays, we need to evaluate them first.

Try this instead:

$elements = [
  "['[email protected]','[email protected]']",
  "['[email protected]','[email protected]']",
];

$emails = collect($elements)
  ->map(function ($element) {
    return (eval("return \$element = " . $element . ';'));
  })
  ->flatten()
  ->all();

Try this:


$elements = [
  ['[email protected]','[email protected]'],
  ['[email protected]','[email protected]'],
];

$emails = collect($elements)->flatten()->all();

This will get you:

=> [
     "[email protected]",
     "[email protected]",
     "[email protected]",
     "[email protected]",
   ]

Check this method on the docs.

  • Related