How to convert Sting Array to PHP Array?
"['a'=>'value one','key2'=>'value two']"
to
$data=['a'=>'value one','key2'=>'value two'];
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?
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.