| re: array_join
"kingofkolt" <jessepNOSPAM@comcast.net> wrote in message
news:dzpyc.77$Hg2.19@attbi_s04...[color=blue]
> "Shmuel" <sdg@nic.fi> wrote in message
> news:R7pyc.2284$7F6.568@reader1.news.jippii.net...[color=green]
> > Hi,
> > I'm trying to do this:
> >
> > $array1 = array("a" => 1, "b" => 2);
> > $array2 = array("a" => 2, "b" => 4);
> > $array3 = array_join($array1, $arra2);
> >
> > Output should be:
> > $array3 = (
> > [a] => 3
> > [b] => 6
> > )
> >
> > with this:
> > function array_join($array1, $array2) {
> > foreach($array2 as $key => $value) {
> > if(array_key_exists($key, $array1)) {
> > $array1[$key] .= $array2[$key];
> > }
> > else {
> > $array[$key] = $array2[$key];
> > }
> > }
> > return $array1;
> > }
> >
> >
> > But it doesn't quite work. Can somebody help a bit?
> > It gives a warning like this:
> >
> > Warning: Invalid argument supplied for foreach() in
> > C:\Programs\work\jobs\index.php on line 63
> >
> > Shmuel.[/color]
>
> you misspelled the variable name $array2 when you called the array_join
> function ("$array2 = array_join($array1,$arra2);") you spelled $array2[/color]
like[color=blue]
> $arra2[/color]
Moreover, .= is string concatenation, not addition. The result would be
$array3 = (
[a] => 12
[b] => 24
)
+= is needed in this case.
function array_join($array1, $array2) {
foreach($array2 as $key => $value) {
@$array1[$key] += $value;
}
return $array1;
} |