musthafa
musthafa

Reputation: 433

Parse Array Formated String as an Array in PHP

I am having an array formatted string stored in a variable where i need to convert it in to real array

here is my code

$hello ="array( 
    'numberposts' => -1, 
    'post_type' => 'post', 
    'meta_query' => array( 
        'relation' => 'AND',
             array( 
                'key' => 'subject_id', 
                'value' => 'CE6301', 
                'compare' => '=' 
                ),
             array( 
                'key' => 'regulation', 
                'value' => '2013', 
                'compare' => '=' 
                ),
             )
    )";

So here is an array that i need to convert as formated array in php

So when my array is printed it should look something like this

Array ( [numberposts] => -1 [post_type] => post [meta_query] => Array ( [relation] => AND [0] => Array ( [key] => subject_id [value] => CE6301 [compare] => = ) [1] => Array ( [key] => regulation [value] => 2013 [compare] => = ) ) )

What function i have to use in php to convert string array into an normal array

Upvotes: 1

Views: 86

Answers (1)

Kevin
Kevin

Reputation: 41903

I don't know how you got hold of this but you can use eval() on this one. Just modify the string a little bit to create a valid array in the end. Example:

$hello ="array( 
    'numberposts' => -1, 
    'post_type' => 'post', 
    'meta_query' => array( 
        'relation' => 'AND',
             array( 
                'key' => 'subject_id', 
                'value' => 'CE6301', 
                'compare' => '=' 
                ),
             array( 
                'key' => 'regulation', 
                'value' => '2013', 
                'compare' => '=' 
                ),
             )
)";

$hello = '$hello = ' . $hello . ';';
eval($hello);
echo '<pre>';
print_r($hello);

Upvotes: 1

Related Questions