/    Sign up×
Community /Pin to ProfileBookmark

How many form elements to process

I have an html form that uses javascript to dynamically add more fields if needed by the user. Now I’m working on some php code to process the POST data that was submitted by the user. I need to know how many form fields were filled out, so I can process them all. My javascript does give each dynamicly added field a unique name and id by incrementing the name, and id by one each time. I can get all of the fields by doing a for each loop like this

foreach($_POST as $name=>$id) {
do something…;
}

I can also count the total amount of fields by using $total = count($_POST);
Neither one of these options works very well. I need to know how many of the dynamically added fields were used, so I can write their contents to a file along with a label (header) for each, as well as echo the values to the screen also with a label. Does anyone have any suggestions?

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@intriviousApr 05.2006 — Maybe this willl help:

Something like this will get everything submitted by either POST or GET, and count how many of each.
[code=php]
$get_count = 0;
foreach ($_GET as $v_name => $v_value) {
$$v_name = $v_value;
$get_count++;
}
$post_count = 0;
foreach ($_POST as $v_name => $v_value) {
$$v_name = $v_value;
$post_count++;
}
[/code]
Copy linkTweet thisAlerts:
@aaronbdavisApr 05.2006 — I would suggest adding a hidden field which you increment each time you dynamically add a new field. Then use this value in a for loop.[code=php]$count = $_GET['the_hidden_field'];
for($i = 0; $i < $count; $i++) {
$localvar = $_GET['field_'.$i];
/*do something*/}[/code]
×

Success!

Help @aaronuni spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...