0

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?

1 Answers1

1

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
        )
)
brombeer
  • 8,716
  • 5
  • 21
  • 27
  • Also, I forgot to mention that `symmetry` here is coming from checkboxes so it can have more than one value like circle, square, oval, rectangle etc. So, considering that little change here does this answer works on that too ? – Shreyansh Kashyap Jan 06 '22 at 10:46
  • You could either just try it out or edit your question and post your "final" `formData`. This code works for the question you posted at this time – brombeer Jan 06 '22 at 10:48
  • I have updated the question.. Please have a look. This is my final data when multiple selections to the check boxes are made. – Shreyansh Kashyap Jan 06 '22 at 10:53
  • Having `symmetry=square&symmetry=circle&symmetry=oval` would leave `symmetry` with the last value, `oval`. Your query should look like `color=red&size=full&symmetry[]=square&symmetry[]=circle&symmetry[]=oval` to make that work – brombeer Jan 06 '22 at 10:56
  • Updated my answer to reflect that – brombeer Jan 06 '22 at 10:59