Search code examples
phpexplodeimplode

Adding Commas And Quotes After Each Element of String List


I have a list like this :

$list = 
"6/17/2017 21:17
6/17/2017 21:14
6/17/2017 21:11
6/17/2017 21:05
6/17/2017 21:03
6/17/2017 20:59
6/17/2017 20:36
6/17/2017 20:35
6/17/2017 20:33";

I need to convert that list into an array. How can I do this? I have way too many elements to do this manually.

Result

$list = array("datetime","datetime");

Solution

  • If the items are separated by new line you can do something like this:

    $items = explode(PHP_EOL, $list);
    

    Please be aware that these constants are defined by the PHP core. It might not work when you change systems. Read more details here

    Best option to cover all cases use this:

    $items = preg_split('/\r\n|\r|\n/', $list);