user1028866
user1028866

Reputation: 795

How do I convert a string of an array to an array in PHP?

This seems like a simple task, but I haven't been able to find a way to do this. I have an output of data stored as a string like this:

$rawData = "array('first' => '$first', 'middle' => '$middle', 'last' => '$last')";

What I simply need to do is convert it to this array:

$arrData = array('first' => "$first", 'middle' => "$middle", 'last' => "$last");

The closest I have been able to get is this shown below with print_r results:

$Data = explode(',', $rawData);

Array
(
    [0] => 'first' => '$first'
    [1] =>  'middle' => '$middle'
    [2] =>  'last' => '$last'
)

What I need is this:

Array
(
    [first] => $first
    [middle] => $middle
    [last] => $last
)

Must be something very easy I have overlooked. Please help.

Upvotes: 0

Views: 101

Answers (2)

Tom
Tom

Reputation: 691

This does what you want ( i think ), even if its not pretty

<?php

$arr = array();
$first = 'one';
$middle = 'two';
$last = 'three';

$rawData = "array('first' => '$first', 'middle' => '$middle', 'last' => '$last')";

$arrData = explode( ',', ( str_replace( array( 'array(\'', '=>', '\')', '\'' ), array( '', '%@@%', '', '' ), $rawData ) ) );

foreach( $arrData as $val ) {
  $v = explode( '%@@%', $val );
  $arr[trim($v[0])] = trim($v[1]);
}

echo '<pre>' . print_r( $arr, true ) . '</pre>';

?>

Upvotes: 1

Axel Amthor
Axel Amthor

Reputation: 11106

Depending on where you get the string from, you may use eval. It's highly recommended to not use this function, whenever the contents of that string may be influenced directly or indirectly by a user, see hint at http://php.net/manual/en/function.eval.php. And it must contain valid PHP syntax, thus putting it into a try/catch block is necessary:

$evalArray = false;
$first = 'a';
$middle = 'b';
$last = 'c';

$rawData = "array('first' => '$first', 'middle' => '$middle', 'last' => '$last')";

try {
    $evalArray = eval($rawData);
} catch ( $e )
{
    echo "parsing failed " . $e
}

print_r($evalArray );

Upvotes: 2

Related Questions