Return to Snippet

Revision: 19154
at October 16, 2009 16:19 by ptepper

Initial Code
use CGI;  

$query = CGI::new(); 

my %fields_temp = $query->Vars;
my %fields      = ();

foreach my $key (keys %fields_temp) {
    if ( $key =~ /(.+)\[\]$/ ) { ## Handle PHP style array inputs 
        if(exists $fields{$1}){
            $fields{$1} = $fields{$1} . ",". $fields_temp{$key};
            $fields{$1} = $fields_temp{$key};
    else {
	$fields{$key} = $fields_temp{$key};

foreach my $key (sort keys %fields) {
    unless ($key =~ /(.+)\[\]$/ ){
	push(@keys, $key);
	push(@values, $fields{$key});

Initial URL

Initial Description
This is inspired by this so I'm using a similar example. In PHP you can combine a set of checkboxes into an array using square brackets like this:

      <input> Red<br>
      <input> Green<br>
      <input> Blue<br>
      <input> Gold<br>

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

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

Initial Tags
php, array, forms, perl

Initial Language