0

I have a really long form in wordpress that is submitted to a third party crm via API.

In some parts, when user press "Yes" or "No" in the form, some fields shown or hidden conditionally, and that modifies the original array.

I would like to know how to remove elements of my array when user press "Yes" or "No". I know i have to use "array_slice", but im really newbie when multidimensional arrays :/

This is my code so far (i changed values but is the same structure):

$body = [
    'array1' => [
        'Name' => user(value),
        'Conditional1' => 'Yes', //if selected "NO" array2 should get removed
        'Conditional2' => 'No', //if selected "NO" array3 should get removed
    ],

    'array2' => [
        'key1' => user(value),
        'key2' => user(value),
        'key3' => user(value),
    ],

    'array3' => [
        [   
            'key1' => user(value),
            'key2' => user(value),
            'key3' => user(value),
        ],
        [   
            'key1' => user(value),
            'key2' => user(value),
            'key3' => user(value),
        ],
    ],
];

//EDITED: THIS WORKS FOR ME:

//remove if conditional1 is no
foreach($body as $key => $value){
    if($value['conditional1'] == 'No'){
        unset($body['array2']);
        }
}
//remove if conditional2 is no
foreach($body as $key => $value){
    if($value['conditional2'] == 'No'){
        unset($body['array3']);
        }
}

Thanks to @El_Vanja advice in the comments section

0xNicko
  • 63
  • 1
  • 7
  • Is there anything dynamic about the top level keys or are they always going to be `array1`, `array2` and `array3`? – El_Vanja Dec 14 '20 at 15:26
  • They are going to be the same names every time. Not change. – 0xNicko Dec 14 '20 at 15:32
  • In that case I'd say you don't need to bother with a generic solution. `if` and `unset` should do the trick. – El_Vanja Dec 14 '20 at 15:41
  • Should I construct a function outside the array or put the condition statement inside the array? Thanks!! – 0xNicko Dec 14 '20 at 15:56
  • 1
    I'm not sure what you mean by that. My point was you don't need to iterate your array or slice if your keys are always going to be known (in your `removeArray` function). – El_Vanja Dec 14 '20 at 16:00

0 Answers0