Search code examples
phparraysloopskeytext-parsing

Parse the first level keys of $_POST, then use the numeric suffix while looping


I have a form that contains a number of fields with names item1, item2, item13, item43 etc, each time those fields are different because they are populated in the form with AJAX.

When user submits I need to perform the following:

foreach ($_POST['itemX']['tagsX'] as $tag) {
    inserttag($tag, X);
}

where X = 1,2,13,43 etc. How can I iterate the $_POST values and perform the above only for the values of those that their name begins with 'item' followed by an the X identifier?

The posted data has the following format:

$_POST = [
    'item38' => ['tags38' => ['aaa', 'bbb']],
    'item40' => ['tags40' => ['ccc', 'ddd']],
    'item1' => ['tags1' => ['eee', 'zzz']],
];

Solution

  • foreach($_POST as $key => $value)
    {
        if (strstr($key, 'item'))
        {
            $x = str_replace('item','',$key);
            inserttag($value, $x);
        }
    }