[Phpwm] updating an array
alan dunn
alan at dunns.co.uk
Fri Oct 20 16:02:30 BST 2006
We made it!! Thanks to everyone who helped - it has taken me 3 days to
get there, but without the group we would still be totally lost.
The final code is quite terse, after wrestling with duplicated arrays,
for_each loops et al, if you care here it is:
Again thank you all for your support.
else
{
if(array_key_exists($e1, $prodarray))
{
$prodarray[$e1] += $q1;
}
// if product does not exist in array - add it
else{$prodarray[$e1] = $q1;}
// now deal with e2
if(!empty($e2))
{
if(array_key_exists($e2, $prodarray))
{
$prodarray[$e2] += $q2;
}
// if product does not exist in array - add it
else{$prodarray[$e2] = $q2;}
}
// now deal with e3
if(!empty($e3))
{
if(array_key_exists($e3, $prodarray))
{
$prodarray[$e3] += $q3;
}
// if product does not exist in array - add it
else{$prodarray[$e3] = $q3;}
}
// now deal with e4
if(!empty($e4))
{
if(array_key_exists($e4, $prodarray))
{
$prodarray[$e4] += $q4;
}
// if product does not exist in array - add it
else{$prodarray[$e4] = $q4;}
}
} // end else
David Long wrote:
> alan dunn wrote:
>> here is my prodarray after the first iteration:
>>
>> Array ( [8x6_blue] => 2 [7x5_blue] => 4 [3x2_and_pass] => 4 [jobcard]
>> => 2 )
>>
>> then my next line has quantity 3 of 8x6_blue
>>
>> now I want to say if 8x6_blue is in_array prodarray (as a key value)
>> add 3 to 2
>>
>> but in_array is saying does 8x6_blue equal '2' or '4' or '4' or '2'
>> which of course it doesn't
>
> You need array_key_exists instead of in_array for this:
>
> // loop through second array
> foreach ($secondarray as $key => $qty)
> {
> if(array_key_exists($key, $prodarray))
> {
> $prodarray[$key] += $qty;
> }
> else
> {
> $prodarray[$key] = $qty;
> }
> }
>
> You could also use isset($prodarray[$key]) in this situation, but in
> cases where null values are used in the array it doesn't quite work as
> you expect (see the isset documentation for more details).
>
> If you don't care about PHP warnings, non-existent array keys return
> NULL, which are converted to 0 if you treat them as an integer, so you
> don't even need to do the test:
>
> // loop through second array
> foreach ($secondarray as $key => $qty)
> {
> $prodarray[$key] += $qty;
> }
>
> Dave
>
>
> _______________________________________________
> Phpwm mailing list
> Phpwm at mailman.lug.org.uk
> https://mailman.lug.org.uk/mailman/listinfo/phpwm
>
>
More information about the Phpwm
mailing list