R00t_R3z R00t_R3z - 4 months ago 13
PHP Question

Assigning an array through foreach PHP

I have the following code:

$data = array();
foreach ($_POST as $field => $value) {
// ex: $field = "1f_fieldname";
if($field[1] == "f")
{
// $field[0] is numeric
$i = $field[0];
$data = array($i => $value);
}
}


the array $data will only print the last element assigned only.

ex:

print_r($data);


prints the following:


array(
[3] => "value3"
)



instead of:


array(
[0] => "value1",

[1] => "value2",
[2] => "value2",
[3] => "value3"
)


What's wrong with it ??

EDIT:
When I print the array from inside the foreach, it prints the whole elements.
But when I print it outside the foreach, it will print only the last one.

Answer

This line is wrong:

$data = array($i => $value);

It replaces the entire array with a new array containing just a single element. It should be:

$data[$i] = $value;

to add a new element to the array. But if you have two keys in $_POST with the same number as the first character (e.g. 1f_fieldA and 1f_fieldB), the later one will replace the first one.