Process PHP-style array (square brackets) from HTML form in Perl CGI


/ Published in: Perl
Save to your folder(s)

This is inspired by this http://www.cgi101.com/book/ch5/text.html so I'm using a similar example. In PHP you can combine a set of checkboxes into an array using square brackets like this:


Red
Green
Blue
Gold



PHP does not do this automatically but it's pretty simple to do if you filter by regular expressions.


Copy this code and paste it in your HTML
  1. use CGI;
  2.  
  3. $query = CGI::new();
  4.  
  5. my %fields_temp = $query->Vars;
  6. my %fields = ();
  7.  
  8. foreach my $key (keys %fields_temp) {
  9. if ( $key =~ /(.+)\[\]$/ ) { ## Handle PHP style array inputs
  10. if(exists $fields{$1}){
  11. $fields{$1} = $fields{$1} . ",". $fields_temp{$key};
  12. }
  13. else{
  14. $fields{$1} = $fields_temp{$key};
  15. }
  16. }
  17. else {
  18. $fields{$key} = $fields_temp{$key};
  19. }
  20. }
  21.  
  22. foreach my $key (sort keys %fields) {
  23. unless ($key =~ /(.+)\[\]$/ ){
  24. push(@keys, $key);
  25. push(@values, $fields{$key});
  26. }
  27. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.