How to get an associative array from a string?

advertisements

This is the initial string:-

NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n

This is my solution although the "=" in the end of the string does not appear in the array

$env = file_get_contents(base_path() . '/.env');

    // Split string on every " " and write into array
    $env = preg_split('/\s+/', $env);

    //create new array to push data in the foreach
    $newArray = array();

    foreach($env as $val){

        // Split string on every "=" and write into array
        $result = preg_split ('/=/', $val);

        if($result[0] && $result[1])
        {
            $newArray[$result[0]] = $result[1];
        }

    }

    print_r($newArray);

This is the result I get:

Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv )

But I need :

Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv= )


You can use the limit parameter of preg_split to make it only split the string once

http://php.net/manual/en/function.preg-split.php

you should change

$result = preg_split ('/=/', $val);

to

$result = preg_split ('/=/', $val, 2);

Hope this helps