This Foreach loop gives all the input $ _POST, how to make it more specific?

I have this code on the HTML side:

<form action="testx.php" method="post"> <input type="hidden" name="block-1" value="001"/> <input type="hidden" name="block-2" value="012"/> <input type="hidden" name="block-3" value="002"/> <input type="hidden" name="block-4" value="005"/> <input type="hidden" name="block-5" value="008"/> <input type="hidden" name="title" value="title goes here"/> <input type="hidden" name="code" value="018439128484"/> <input type="submit" value="Finish!" class="submit-btn" /> </form> 

and I have this Foreach loop on the PHP side:

 <?php $i=0; foreach($_POST as $name => $value) { echo $i . " - " . $name . ": " . $value . "<br>"; $i++; } ?> 

Unfortunately, this Foreach loop handles all inputs ... how to make this loop ONLY run inputs with the name "block-X"?

I tried to try like this, but failed:

 $i=0; $x = 'block-'.$i+1; foreach($_POST[$x] as $name => $value) 

he says: Warning: invalid argument provided by foreach ()

thanks!

0
source share
3 answers

Try filtering $name inside a loop, for example strpos :

 <?php $i=0; foreach($_POST as $name => $value) { if(strpos($name, 'block-')===0) { echo $i . " - " . $name . ": " . $value . "<br>"; $i++; } } ?> 
+4
source

The only way I see now:

 foreach($_POST as $name => $value) { if(substr($name, 0, 5) == "block"){ echo $i . " - " . $name . ": " . $value . "<br>"; $i++; } } 

Edit: Someone is faster than me: x

Another solution to avoid string comparisons

 while(isset($_POST["block-".$i])){ echo $i . " - block-" . $i . ": " . $_POST["block-".$i] . "<br>"; $i++; } 
+2
source

All other answers are incorrect.

You have 5 specific directions that interest you. They are numerical and sequential. You want iterations from 1 to 5. You do not want to iterate over the entire $_POST array, selectively skipping keys, and you absolutely do not want to include regular expressions in such a trivial task. Every answer that uses regular expressions to solve this problem is incorrect, and those that use strpos are not much better.

Use this:

 for ($i = 1; $i <= 5; ++$i) { echo "$i = block-$i: ", $_POST["block-$i"]; } 
+1
source

Source: https://habr.com/ru/post/1483733/


All Articles