tags:

views:

54

answers:

3

Hi, I want to receive unlimited $_POST variables including an additional number and turn them into arrays like paypal form does.

Example:

<form action="mysite">
<input name="productname" />
<input name="productname1" />
<input name="productname2" />
Etc....
</form>

I will turn that into a php array after receiving it:

products(gta,twilight,flowers,chocolate,ipod)

So that just to explain you, i want to list them as an invoice.

Note: Please don't suggest to use the productname[], i want to use preg match to do that Thanks

+4  A: 
<form action="mysite">
<input name="productname[]" />
<input name="productname[]" />
<input name="productname[]" />
Etc....
</form>

Then $_POST['productname'] will be a numeric array with all your values.

If you can't control the form, you can build the array like this:

$res = array();
foreach ($_POST as $k => $v) {
    if (preg_match('/^productname(\d{0,})$/', $k, $matches))
        $res[(int) $matches[1]] = $v;
}
// result in $res
Artefacto
Hi, i already know that, i wanna programatically to turn that into array using some preg match or something... thanks!
David
@David, can you clarify? `$_POST['productname']` will already be an array. You don't need to use `preg_match`.
Matthew Flaschen
I know that, but i want the form to be like paypal, they should add numbers to the end of variable
David
@David Why the hell would you want to replace an easily iterable structure like an array with that?...
Artefacto
Because i don't have control to the form =D !!!!
David
@David OK, I've edited.
Artefacto
Thanks that works like magic, Thanks a lot!
David
A: 

If they don't actually have to have numbers in the names, use:

<form action="mysite">
<input name="productname[]" />
<input name="productname[]" />
<input name="productname[]" />
Etc....
</form>

PHP will convert productname to an array. The FAQ has more info on this feature.

Matthew Flaschen
Hi, i already know that, i wanna programatically to turn that into array using some preg match or something... thanks!
David
+1  A: 
<?php
foreach($_POST as $name => $value) {
    if(strpos($name, 'productname') === 0) {
        // Do something with it
    }
}
?>
Matt Williamson