Norman
Norman

Reputation: 6365

PHP Looping through a forms text fields only

Suppose I have a form like this:

echo "<form action='form_rec.php' method='post'>";

//These fields are dynamically generated du5, du6 etc...
echo '<input type="text" name="du1" value="125"><br>';
echo '<input type="text" name="du2" value="326"><br>';
echo '<input type="text" name="du3" value="090"><br>';
echo '<input type="text" name="du4" value="425"><br>';

echo "<input type='hidden' name='input' value='key'>";
echo "<input type='submit' class='button' name='submit' value='submit'>";
echo "</form>";

how can I loop through only the type="text" fields using php. The output i'm trying to achieve is:

du1 125
du2 326
du3 090
du4 425

I'm currently doing it like this:

foreach($_POST as $key =>$value){
    echo $key.' '.$value.'<br>';
}

but this outputs the hidden key as well as the submit button's values

du1 125
du2 326
du3 090
du4 425
input key
submit submit

How can i get only the type="text" fields name and value?

Upvotes: 0

Views: 60

Answers (2)

user9110002
user9110002

Reputation:

Because all the text input names have a common substring ('du'), you can use strpos to check if this substring exists or not, i.e. if $key has the substring 'du' it refers to input text otherwise not.

Try this:

foreach($_POST as $key =>$value){
    $myString = 'du'; //the substring common to all the text elements (du1,du2,du3,du4)
    if (strpos($key, $myString) === 0){ //strpos finds the position of a substring in a string ('du' position is at offset zero)
        echo $key.' '.$value.'<br>';
    }
}

In this case, strpos will returns zero for input $key (because zero is the offset of the substring 'du') and will returns FALSE for hidden input $key and submit input $key (because the substring 'du' is not present).

This solution allows you not to change inputs name.

Please note the use of ===, using == will not exclude the FALSE results for either hidden input and submit input infact FALSE == 0 will return TRUE

check this note from the PHP: strpos manual:

Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Upvotes: 0

revo
revo

Reputation: 48711

You can either prepend a specifier string to text input fields before submitting form e.g. text-125, text-090... or use an array:

echo '<input type="text" name="du[]" value="125"><br>';
echo '<input type="text" name="du[]" value="326"><br>';
echo '<input type="text" name="du[]" value="090"><br>';
echo '<input type="text" name="du[]" value="425"><br>';

Otherwise there should be a condition using e.g. preg_match():

foreach($_POST as $key => $value) {
    if (preg_match('~^du\d*$~', $key))
        echo "{$key} {$value}<br>";
}

Upvotes: 2

Related Questions