Reputation: 84
I'm using an online shopping cart which takes items ordered and passes their unique ID through the URL to a process.php page. So the URL would look something like
process.php?code_1=231&code_2=532&code_3=342
Another code_x=xxx
is generated for each item ordered. On the process.php page, how would I create an array to get the values of the code_x
without knowing how many items are ordered?
Upvotes: 3
Views: 589
Reputation: 3421
You have to iterate through $_GET and look for names.
foreach(!empty($_GET as $name=>$value)) {
// Check for match names for your
if (preg_match('/^code_[1-9]$/', $name)) {
// Do whatever with values
}
}
Upvotes: 1
Reputation: 437386
This problem is much better solved by changing the names of the elements in your form to code[]
.
For example, where you now have let's say
<input type="text" name="code_1" ... />
<input type="text" name="code_2" ... />
<input type="text" name="code_3" ... />
You would change that to
<input type="text" name="code[]" ... />
<input type="text" name="code[]" ... />
<input type="text" name="code[]" ... />
After doing this, $_GET['code']
will be an array which contains all the values from the text boxes as its items.
Update:
If you cannot control the names of the incoming parameters, you need to parse manually. Here's how I would do it:
// Sample data
$get = array('code_1' => 'foo', 'code_2' => 'bar', 'code_X' => 'X', 'asdf' => 'X');
$codes = array();
foreach($get as $k => $v) {
// Reject items not starting with prefix
if (substr($k, 0, 5) != 'code_') {
continue;
}
// Reject items like code_X where X is not all digits
$k = substr($k, 5);
if (!ctype_digit($k)) {
continue;
}
$codes[$k] = $v;
}
print_r($codes);
Upvotes: 8
Reputation: 3608
print_r($_GET);
foreach($_GET as $key=>$val)
{
echo '<br />';
echo $key.' : '.$val;
}
Upvotes: 1
Reputation: 72662
It would be much better to use an array like Jon suggested.
It also would be cleaner to not use get
for this. But rather post
.
However if you really want to go this route you could do:
foreach($_GET as $name=>$value) {
if (strpos($name, 'code_') !== 0) continue;
// here are the names and values of the items
}
However again: I would not recommend it.
Upvotes: 4