Natalia
Natalia

Reputation: 417

loop through $_POST variables with similar names

I have several $_POST variables, they are

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

and so on

I need to write a loop tha displays the values of all the variables (I don't know how many there are). What would be a simplest way to go about it? Also what would be the simplest way if I do know how many variables I have?

Upvotes: 3

Views: 13859

Answers (7)

user3472684
user3472684

Reputation: 1

try:

while (list($key,$value) = each($_POST))
   ${$key} = trim($value);

Upvotes: 0

ghstcode
ghstcode

Reputation: 2912

try:

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

In the above example, $k will be the array key and $v would be the value.

Upvotes: 2

goat
goat

Reputation: 31813

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']);

Upvotes: 1

SlavaNov
SlavaNov

Reputation: 2485

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

Upvotes: 4

macjohn
macjohn

Reputation: 1803

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];
  }
}

Upvotes: 1

Rob Hruska
Rob Hruska

Reputation: 120286

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()

Upvotes: 16

Don Wilson
Don Wilson

Reputation: 552

foreach($_POST as $k => $v) {
    if(preg_match("#item_number([0-9]+)#si", $k, $keyMatch)) {
        $number = $keyMatch[1];

        // ...
    }
}

Upvotes: 0

Related Questions