Search code examples
phparrayslaravellaravel-livewire

How to convert String Array to php Array?


How to convert Sting Array to PHP Array?

"['a'=>'value one','key2'=>'value two']"

to

$data=['a'=>'value one','key2'=>'value two'];

Please let me know if anyone knows of any solution


I want to take array input via textarea. And I want to convert that to a PHP array.

When I'm through textarea

['a'=>'value one','key2'=>'value two']

This is happening after submitting the from

"['a'=>'value one','key2'=>'value two']"

Now how do I convert from this to PHP Array?


Solution

  • Assuming you are not allowing multi dimensional arrays, this will work:

    $stringArray = "['a'=>'value one','key2'=>'value two']";
    $array = array();
    
    $trimmedStringArray = trim( $stringArray, '[]' );
    $splitStringArray = explode( ',', $trimmedStringArray );
    foreach( $splitStringArray as $nameValuePair ){
        list( $key, $value ) = explode( '=>', $nameValuePair );
        $array[$key] = $value;
    }
    

    Output:

    Array
    (
        ['a'] => 'value one'
        ['key2'] => 'value two'
    )
    

    You will probably want to do some error checking to make sure the input is in the correct format before you process the input.