I've been working a lot with forms lately and decided to make a php script to simplify some aspects that I see myself repeating, I won't post the full monstrosity that I have created, but instead I will ask you to help me simplify the following code if possible:
function add($name,$input,&$array)
{
$p = explode('[',$name);
if(isset($p[1]))
{
list($key) = explode(']',$p[1]);
if(ctype_digit($key))
{
$array['forms'][$p[0]][$key] = $input;
}else{
$array['forms'][$p[0]][] = $input;
}
}else{
$array['forms'][$name] = $input;
}
}
$array = array();
add('image[]','',$array);
add('image[8]','',$array);
add('image[1]','',$array);
add('image[]','',$array);
echo '<PLAINTEXT>';
print_r($array);
it makes $array into:
Array
(
[forms] => Array
(
[image] => Array
(
[0] =>
[8] =>
[1] =>
[9] =>
)
)
)
the problem here is that if you add a "image" as the $name, then it must be added to the array as if it was Posted, so it will be array(image=>data), if you enter image[], then it will be array(image=>array(0=>data)).
I find my code to be way too bulky, I found parse_str, which parses the "image[]", but it did not serve me as I need the names to be added separately...
Can this function be made more elegant?
clarification:
Is there a better way to add "name[]" into a array as if it was part of a list of names to be added to the array.
so I need a parse_str replacement that does not overwrite the $array. Example:
$array = array();
parse_str('image[]=test',$array);
parse_str('image[]=test1',$array);
parse_str('image[]=test2',$array);
but the result looks like:
Array
(
[image] => Array
(
[0] => test2
)
)
but needs to look like:
Array
(
[image] => Array
(
[0] => test
[1] => test1
[2] => test2
)
)
This would really simplify the above function!