loop through $_POST variables with similar names

后端 未结 7 817
南笙
南笙 2020-12-18 09:51

I have several $_POST variables, they are

$_POST[\'item_number1\']
$_POST[\'item_number2\']

and so on

I need to write a loop tha di

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 10:13

    If you must stick with those variable names like item_numberX

    foreach (array_intersect_key($_POST, preg_grep('#^item_number\d+$#D', array_keys($_POST))) as $k => $v) {
        echo "$k $v \n";
    }
    

    or

    foreach (new RegexIterator(new ArrayIterator($_POST), '#^a\d+$#D', null, RegexIterator::USE_KEY) as $k => $v) {
        echo "$k $v \n";
    }
    

    Better to use php's input variable array feature, if you can control the input names.

    
    
    
    

    then php processes it into an array for you.

    print_r($_POST['item_number']);
    

提交回复
热议问题