Posted By

ptepper on 10/16/09


Tagged

php array forms perl cgi


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

ringo380


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


 / Published in: Perl
 

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.

  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  

You need to login to post a comment.