[Phpwm] updating an array
David Long
dave at longwaveconsulting.com
Fri Oct 20 12:47:37 BST 2006
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
More information about the Phpwm
mailing list