loop through $_POST variables with similar names

后端 未结 7 767
南笙
南笙 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 09:55

    if you know the number of variables:

    <?php
    $n = 25; // the max number of variables
    $name = 'item_number';  // the name of variables
    for ($i = 1; $i <= $n; $i++) {
      if (isset($_POST[$name . $i])) {
        echo $_POST[$name . $i];
      }
    }
    

    if you don't know the number:

    <?php
    $name = 'item_number';
    foreach ($_POST as $key) {
      if (strpos($key, $name) > 0) {
        echo $_POST[$key];
      }
    }
    
    0 讨论(0)
  • 2020-12-18 09:58

    If you know how many do you have:

    for ($i=0; $i < $num_of_vars; $i++)
        echo $_POST['item_number'.$i]."<br />";
    

    UPDATE: If not:

    foreach($_POST as $k => $v) {
        $pos = strpos($k, "item_number");
        if($pos === 0)
            echo $v."<br />";
    }
    

    Gets all POST variables that are like "item_number"

    UPD 2: Changed "==" to "===" because of piotrekkr's comment. Thanks

    0 讨论(0)
  • 2020-12-18 10:02

    This will echo all POST parameters whose names start with item_number:

    foreach($_POST as $k => $v) {
        if(strpos($k, 'item_number') === 0) {
            echo "$k = $v";
        }
    }
    

    PHP Manual: foreach(), strpos()

    0 讨论(0)
  • 2020-12-18 10:06

    try:

    while (list($key,$value) = each($_POST))
       ${$key} = trim($value);
    
    0 讨论(0)
  • 2020-12-18 10:11
    foreach($_POST as $k => $v) {
        if(preg_match("#item_number([0-9]+)#si", $k, $keyMatch)) {
            $number = $keyMatch[1];
    
            // ...
        }
    }
    
    0 讨论(0)
  • 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.

    <input name="item_number[]">
    <input name="item_number[]">
    <input name="item_number[]">
    

    then php processes it into an array for you.

    print_r($_POST['item_number']);
    
    0 讨论(0)
提交回复
热议问题