Search code examples
phparraysserializationform-serialize

Get form serialize value from the array list


I have an array like this:

Array
(
    [action_name] => edit
    [formData] => color=red&size=full&symmetry=square&symmetry=circle&symmetry=oval
)

Here, form data is coming using the serialize method of JS and so it is displayed like above. I want to get each data from the formData key. How can I get that?

I tried:

$_POST['formData']['color']

But that is not working. I think the method to fetch this shall be different. How can I do that?


Solution

  • You can use parse_​str to "parse string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided)."

    <?php
    $_POST = [
        'action_name' => 'edit',
        'formData' => 'color=red&size=full&symmetry=square',
    ];
    parse_str($_POST['formData'], $parsed);
    print_r($parsed);
    

    will output

    Array
    (
        [color] => red
        [size] => full
        [symmetry] => square
    )
    

    Edit: Having multiple values for symmetry, your query should look like:

    <?php
    $_POST = [
        'action_name' => 'edit',
        'formData' => 'color=red&size=full&symmetry[]=square&symmetry[]=circle&symmetry[]=oval',
    ];
    parse_str($_POST['formData'], $parsed);
    print_r($parsed);
    

    This would output:

    Array
    (
        [color] => red
        [size] => full
        [symmetry] => Array
            (
                [0] => square
                [1] => circle
                [2] => oval
            )
    )