loop through $_POST variables with similar names - php

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?

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

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

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.

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

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

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

Related

How do I get final value of += operator in php?

I want to get final value of $score in the code below
foreach($request->jawaban as $key => $value){
$soal = Soal::find($key);
$kunci = $soal->kunci;
$score = 0;
if($value === $kunci){
$score+=1;
echo $score;
}
}
but its produce value
123456789101112131415161718192021
how do I get 21 value only?
Based on what others have said: But just to show you the full code
$score = 0; //define this before the loop
foreach($request->jawaban as $key => $value){
$soal = Soal::find($key);
$kunci = $soal->kunci;
if($value === $kunci) $score+=1; //simplify this, as I am lazy coder.
}
echo $score; //echo the final value, after the loop finishes.
Good Luck.
You need to echo after loop. As below:
$score = 0; //define this variable before loop
foreach($request->jawaban as $key => $value){
$soal = Soal::find($key);
$kunci = $soal->kunci;
if($value === $kunci){
$score+=1;
}
}
echo $score; // echo after loop end
Hope it helps you.
Initialize $score before the loop and also print the output after loop.
$score = 0;
foreach($request->jawaban as $key => $value){
$soal = Soal::find($key);
$kunci = $soal->kunci;
if($value === $kunci){
$score+=1;
}
}
echo $score;

Foreach Array only receive last key

This is a first time i get this error ,I have array with 5 element, but when i use Foreach, it's only receive last element. I want to get all key in array $datas['datas'].
echo count($datas['datas']);
[![var_dump($datas['datas']);
$test = 0;
foreach ($datas['datas'] as $k => $v);
{
echo $k;
$test++;
}
dd($test)];
You have a incorrect ";" character on line 6:
foreach ($datas['datas'] as $k => $v);
Your code should be:
echo count($datas['datas']);
$test = 0;
foreach ($datas['datas'] as $k => $v)
{
echo $k;
$test++;
}
dd($test);
Because you are not assigning the value to your variable:
Please replace this loop
foreach ($datas\['datas'\] as $k => $v)
{
echo $k;
$test++;
}
dd($test);
By this:
foreach ($datas['datas'] as $k => $v)
{
echo $k;
$test['keys'] = $k;
}
dd($test['keys']); // now your full data will be in test variable
and Try hoe it will work.

Nested foreach loop displaying duplicate results php

I have function that is supposed to match arrays together using the array_intersect function. I'm trying to match a product name with possible offers with same name from multiple merchants. My issue now is I'm using nested foreach loops and whenever I run it, the loop is always infinite and it prints duplicate results.
Here's the function:
function get_matching_product3(&$catalogue, $stock) {
$stockSmallCase = array_map('strtolower', $stock);
$catalogueSmallCase = array_map('strtolower', $catalogue);
foreach ($catalogueSmallCase as $key => $value)
{
$catalogueKey = $key;
$catalogueValue = $value;
$catalogueTokens = explode (' ', $catalogueValue);
foreach ($stockSmallCase as $key => $value) {
$stockKey = $key;
$stockValue = $value;
$stockTokens = explode (' ', $stockValue);
$match= array_intersect($stockTokens, $catalogueTokens);
$m = count($match);
$t = count($catalogueTokens);
//echo $m;
//echo $t;
if (($m > 1) && (($m / $t) * 100) >= 90) {
//print_r($match);
echo = $catalogueKey." ".$stockKey;
//echo "</br>";
//echo $stockKey;
}
}
}
return null;
}
You have
foreach ($catalogueSmallCase as $key => $value)
and
foreach ($stockSmallCase as $key => $value)
I think the problem came from the $key and $value variables. They are probably misunderstood by php at some time of the loop.
Try changing it in order to différenciates it.

foreach trying to make 3 parameters

Is there a way I could make this happen? Its like foreach with 3 paramaters
Something like this
foreach ($value as $v,$value2 as $v2,$value3 as $v3)
<?php echo $v->name?>
<?php echo $v->actual?>
<?php echo $v2->estimated?>
<?php echo $v3->projected?>
I think you want
foreach ($value as $v)
{
foreach($value2 as $v2)
{
foreach($value3 as $v3)
{
echo $v->name;
echo $v->actual;
echo $v2->estimated;
echo $v3->projected;
}
}
}
Or:
foreach ($value as $v,$value2 as $v2,$value3 as $v3)
{
echo $v->name;
echo $v->actual;
}
foreach($value2 as $v2)
{
echo $v2->projected;
}
foreach($value3 as $v3)
{
echo $v3->estimated;
}
Which you may have known, but I don't think it's possible to actually put all three into one like you're asking.
EDIT: With a bit more information on what your $value arrays contain, it may be easier to provide you with a solution that can help you more easily accomplish what you're trying to do.
To retrieve next elements from each array in every iteration:
do{
$v = current($value);
$v2 = current($value2);
$v3 = current($value3);
// ...
} while(next($value) !== false && next($value2) !== false && next($value3) !== false);
Assuming they have equal length, are not empty and contain no falses.
You may also want to use for loop:
for($i = 0; $i < count($value); $i++){
$v = $value[$i];
$v2 = $value2[$i];
$v3 = $value3[$i];
// ...
}
Assuming their keys are numeric and they have equal length.

Process array starting with second entry?

I have an array in PHP and would like to use foreach to process entries skipping [0], to process [1], [2], etc.
Thank you
you can use array_slice
$array = array(1,2,3);
foreach (array_slice($array,1) as $value ) {
echo $value;
}
If you don't mind losing first element you can use array_shift
array_shift($array);
foreach ( $array as $value ) {
echo $value;
}
Output
23
$i = 0;
foreach ($ar as $value) {
if ($i > 0) {
// code here
}
$i++;
}
You can keep a variable for this:
$firstSkipped = false;
foreach ($arr as $value) {
if (!$firstSkipped) {
$firstSkipped = true;
continue;
}
// code here
}
Or you could just use a regular for loop, setting the beginning counter to 1:
for ($i = 1, $count = count($arr); $i < $count; $i++) {
// code here
}
You can remove the first entry from an array with array_shift.
$array = array("a","b","c");
array_shift($array);
foreach ($array as $values)
{
echo $values; //bc
}
Try this:
$arr = array(0,1,2,3,4,5);
unset($arr[0]);
foreach($arr as $value) {
echo $value;
echo "<br />";
}
This would delete first entry from array, so it would not skip as you asked, but anyway you can try this...

Categories