Home >Backend Development >PHP Tutorial >How to Convert a PHP `print_r()` String Output Back into an Array?
How to Convert a String Representation of an Array Back to an Array
In PHP, when you print an array using print_r(), it converts it into a visually-formatted string. While useful for debugging, this string format is not directly convertible back to an array. However, with some custom parsing logic, it is possible to recreate the original array.
A custom function, text_to_array(), was developed to tackle this conversion. It operates by:
Parsing the String:
Creating the New Array:
Example Usage:
Consider the following array:
$a = ['foo' => 'fooMe'];
After converting it to a string using print_r(), you get:
Array ( [foo] => fooMe )
Passing this string to the text_to_array() function will result in the original array:
$b = text_to_array('Array ( [foo] => fooMe )'); print_r($b);
This outputs:
Array ( [foo] => fooMe )
By implementing this custom parsing logic, you can recreate an array from its printed string representation, enabling you to restore array functionality even after debugging.
The above is the detailed content of How to Convert a PHP `print_r()` String Output Back into an Array?. For more information, please follow other related articles on the PHP Chinese website!