Home >Backend Development >PHP Tutorial >How to Convert a String Representation of an Array Back into an Array in PHP?

How to Convert a String Representation of an Array Back into an Array in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-04 08:21:13276browse

How to Convert a String Representation of an Array Back into an Array in PHP?

How to Extract an Array from a Printed Representation

Given an array, you may wish to print its contents using the print_r() function. However, the resulting output will be a string representation of the array.

To convert this string back into an array, you can utilize a custom function such as the one shown below:

function text_to_array($str) {

    // Initialize arrays
    $keys = array();
    $values = array();
    $output = array();

    // Check if the input is an array
    if( substr($str, 0, 5) == 'Array' ) {

        // Parse the input
        $array_contents = substr($str, 7, -2);
        $array_contents = str_replace(array('[', ']', '=>'), array('#!#', '#?#', ''), $array_contents);
        $array_fields = explode("#!#", $array_contents);

        // Process each array field
        for($i = 0; $i < count($array_fields); $i++ ) {

            // Skip the first field (it's empty)
            if( $i != 0 ) {

                $bits = explode('#?#', $array_fields[$i]);
                if( $bits[0] != '' ) $output[$bits[0]] = $bits[1];

            }
        }
    }

    return $output;
}

By calling this function with the printed representation of your array as an argument, you can obtain the original array data:

$array_string = print_r($original_array, true);
$new_array = text_to_array($array_string);

The above is the detailed content of How to Convert a String Representation of an Array Back into an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn