How can I get form values by loops in PHP

Viewed 51

How can I get only the test# inputs without the email and password by

<form method="get">
    <input type="email" placeholder="email" name="email">
    <input type="password" placeholder="passsword" name="passsword">
    <input type="text" placeholder="test 1" name="test#1">
    <input type="text" placeholder="test 2" name="test#2">
    <input type="text" placeholder="test 3" name="test#3">
    <input type="text" placeholder="test 4" name="test#4">
    <input type="text" placeholder="test 5" name="test#5">
    <input type="text" placeholder="test 6" name="test#6">
    <input type="text" placeholder="test 7" name="test#7">
    <input type="text" placeholder="test 8" name="test#8">
    <input type="text" placeholder="test 9" name="test#9">
    <input type="text" placeholder="test 10" name="test#10">
    <button name="submit" type="submit">submit</button>
</form>

I tried foreach but it gets all values

3 Answers

You could filter by array key:

$testFields = array_filter($_POST, function($key){
    return strpos($key, 'test#') === 0;
}, ARRAY_FILTER_USE_KEY);

But I would instead suggest (as written in the comments) that you name your fields "test[]" and iterate over those:

foreach($_POST['test'] as $val){

}

PHP automatically gives you an array of fields with "[]" at the end of their name.

You can name all same inputs with same name like this

<input type="text" placeholder="test 2" name="test[]">

and then in php you can get input as

if($_POST['test']){
    foreach($_POST['test'] as $test){
        print_r($test)
    }
}
<?php
if (isset($_GET['submit'])) {
    for ($i = 1; $i <= 10; $i++) {
        $value = $i . '#test';
        echo $_GET[$value]."<br>";
    }
}
?>
Related