Reputation: 335
I have a form which submits a status and a id as arrays to an update.php. Below is the submitting form input and the sent URL
<? echo"<input type='hidden' name='status[]' value='$status' />"; ?>
<? echo"<input type='hidden' name='id[]' value='$id' />"; ?>
update_pnr.php?status%5B%5D=0&id%5B%5D=4&status%5B%5D=0&id%5B%5D=5
The PHP which should update the incoming information is:
$newarr = array_combine($_GET['status'],$_GET['id']);
foreach($newarr as $index => $value){
echo 'index: ' . $index . 'Value: ' . $value . '<br>';
}
I was expecting:
0 Value: 4
0 Value: 5
But the first line is ignored, I receive only the last line. Why is that ?
Upvotes: 0
Views: 235
Reputation: 9351
As far doc array_combine
Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.
http://php.net/manual/en/function.array-combine.php
First parameter array's value is use as keys and second parameter array's value use as values
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
Output:
Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)
Your scenario is:
Your array $_GET['status']
:
Array(
[0] => 0
[1] => 0
)
array $_GET['id']
:
Array
(
[0] => 4
[1] => 5
)
After combine it becomes:
Array
(
[0] => 5
)
Because array status has same value twice which are the keys of combined array. Since key is unique it overwrite with the last value:
$newarr[0] => 4
and then $newarr[0] => 5
$newarr[0] => 4
overwrite by
$newarr[0] => 5
and $newarr
has only one key and value.
Upvotes: 2
Reputation: 905
A possible workaround:
foreach($_GET['status'] as $key => $val)
echo $val . 'Value: ' . $_GET['id'][$key];
Upvotes: 1