PHP loop statements for form variables

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
seandisanti
php-forum Fan User
php-forum Fan User
Posts: 973
Joined: Mon Oct 01, 2012 12:32 pm

Tue Oct 13, 2015 9:07 am

you can just do something like this in your form handler:

Code: Select all

<?php
// if no get parameters passed, nothing to do
if (!$_GET){
   die('Nothing to see here');
}
// don't want to handle arbitrary arguments, just the ones we expect
// this is the very least you should do for input validation
$allowed = array('color1','color2','color3');
// empty array of colors
$colors = array();

// loop through passed parameters
foreach ($_GET as $key=>$value){
   // stop processing at any invalid input
   if (! in_array($key,$allowed)){
      echo "I don't care about your stupid $key";
      exit;
   }
   // or add to array
   $colors[$key] = $value;
}
// and then do whatever with it
echo 'Your color array:<pre>';
print_r($colors);
 

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 973
Joined: Mon Oct 01, 2012 12:32 pm

Tue Oct 20, 2015 11:03 am

Yes, just set your form element names and values accordingly

Post Reply