I have several $_POST variables, they are
$_POST[\'item_number1\']
$_POST[\'item_number2\']
and so on
I need to write a loop tha di
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];
}
}
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
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()
try:
while (list($key,$value) = each($_POST))
${$key} = trim($value);
foreach($_POST as $k => $v) {
if(preg_match("#item_number([0-9]+)#si", $k, $keyMatch)) {
$number = $keyMatch[1];
// ...
}
}
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']);