0

I have a function like this:

function array2string($data) {
    if($data == '') return '';
    return addslashes(var_export($data, TRUE));
}

I invoke this function convert $_REQUEST Array to String just like

array2string($_REQUEST)

and convert the result String to Array use this function:

function string2array($data) {
    // print_r($data);
    $data=str_replace('\'',"'",$data);
    // $data=str_replace(''',"'",$data); // add by futan 2015-04-28
    $data=str_replace("\'","'",$data);
     // print_r($data);exit();
    if($data == "") return array();
    @eval("\$array = $data;");
    return $array;
}

Generally, it can work, bur sometimes,it doesn't work.
the result like this:

array (  \'name\' => \'xxx

I cant find any problem, because I cant recurrence error. someone can help me??

5
  • 7
    Whats the purpose of using these functions? You could use serialize() and unserialize() instead if you want string representation of the array data and vice versa. Commented Jun 8, 2015 at 4:26
  • 3
    Agree or even can use json_encode and json_decode. Commented Jun 8, 2015 at 4:30
  • @Ulver I want to save array in database as String. Commented Jun 8, 2015 at 5:29
  • Yes you should use serialize() for that purpose. I will post an answer shortly. Commented Jun 8, 2015 at 6:08
  • @Ulver I have used this function in my project , and many datas saved in database. Commented Jun 8, 2015 at 6:14

2 Answers 2

3

Instead of creating your own custom function to get the string representation of the array/object and vice versa, you should use the PHP native serialize() / unserialize() for that purpose:

// Serialize the array data. This string can be used to store it in the db
$serialised_string = serialize($_REQUEST);

// Get the array data back from the serialized string
$array_data = unserialize($serialised_string);

Also you could run into PHP injection issues by eval() usage in your custom function string2array().

Sign up to request clarification or add additional context in comments.

Comments

0

Another alternative besides serialize would be to use json_encode:

 $array = ['foo' => 'bar'];
 $string = json_encode($array); // $string now has {'foo': 'bar'}

 // Restore array from string. 
 // Second parameter is passed to make sure it's array and not stdClass
 $array = json_decode($string, true); 

Don't invent your function unless you absolutely need to. If you think you do, please add an explanation, why, so that we can help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.