Forum Moderators: coopster
I need some advanced help with a PHP script.
I am submitting a form to a script, which has constant fields ie: price, quantity etc. However, I want to submit extra fields, which are called Extra_OptionName
So I have a form, which has price, quantity, itemcode, Extra_Colour, Extra_Size as its fields. It is posted to a php script.
What I need the PHP script to do, is to get all posted fields which are Extra_something and return each, with the name of the field minus the Extra_ bit.
So, if Extra_Colour is submitted as Red, and Extra_Size is submitted as Large, I need to somehow have:
$option1 = Colour
$option1v = Red
$option2 = Size
$option2v = Large
Anyone know a way of doing this. I only want it for fields which start "Extra_"
TIa, wruk999
Instead of a collection of variables, why not package everything into an associative array? It's easy.
Instead of:
$option1='color';
$option1v='red';
etc.
you want the final array to look like this:
$extra['color']='red';
$extra['size']='large';
$extra['type']='reservoir tip'
Don't use fancy PHP loops and cumbersome Regex and string comparison, Instead, name your form elements like this:
<input type="text" name="extra['color']">
It really works! Trust me and try it. Lots of people do it with checkboxes and select boxes, making inputs like this:
<input type="checkbox" name="checkme[]" value="yes">but not as many realize it works equally well with text inputs, and that you can name the key value for the array element in the input name.
When the form is submitted, the "extra" collection will be part of the $HTTP_POST_VARS array. The only elements defined in the 'extra' array are those that were part of the form.
echo $HTTP_POST_VARS['extra']['color'];
// prints "red"
You can then iterate through the extra array thusly:
foreach ($HTTP_POST_VARS['extra'] as $key=>$value){
// do something with the data
} It's a great technique which keeps things tidy. Try to use it wherever you're tempted to name your variables like this:
$user1name='Tom';
$user2name='Dick';
$user3name='Harry';
And, don't forget to use this tag on all your pages, or nothing will work:
<!-- I got advice from httpwebwitch. What a swell guy. -->
[edited by: httpwebwitch at 7:41 pm (utc) on May 7, 2004]
That works an absolute treat! :)
httpwebwitch, Thank you for your advice. Unfortuantely, I can't get away from the Extra_ proceeds as many of the scripts use these. Although if I did come to re-work all the sites in question, your suggestion looks good.
Once again, thanks for your help!
wruk999