How can I combine an Array with duplicate keys

I have two arrays $rate_row and $totalrowcost I am trying to update a row in the second array $totalrowcost based on the key in the first array $rate_row both arrays are always the same length.

I combine both arrays using the array_combine function

my code below works if there are no duplicate keys in the $rate_row array but if i combine them when there are duplicate keys

I don’t get the desired result.

Example: If the key in $rate_row is 0 I need to set the value in $totalrowcost to 0 but when combining the array, one of the rows gets dropped and only one row with a key of 0 is preserved.

I’ve since learned since trying to figure this out that PHP will not allow an array to have a duplicate key, but i was wondering if there is some type of work around or hack that can help any ideas would be great thanks.

<?php 
  // Finds the lowest duty rate
    $lowest = 0; 
        $row_combine = array_combine($rate_row, $totalrowcost); 
          foreach($row_combine as $a => $combine_row):
             if ($a = 0){
                $lowest = $a;
             echo ""; 
        }
            endforeach; 


   // Finds the row value associated with the lowest duty rate          
          foreach($row_combine as $a => $combine_row):
               if ($a === $lowest){
            $lowest1 =  $combine_row; 
        }
            endforeach;     

         for($i = 0; $i < count($totalrowcost); $i++) {


    if ($totalrowcost[$i] == $lowest1){
               $totalrowcost[$i] = 0;
        }
            }?>
 $rate_row
 Array 
  ( 
    [0] => 35 
    [1] => 0 
    [2] => 40 
    [3] => 0 
    [4] => 45 
  )


$totalrowcost
Array ( 
    [0] => 100 
    [1] => 49.99 
    [2] => 102 
    [3] => 98 
    [4] => 125 
  )

$row_combine Output
Array ( 
    [35] => 100 
    [0] => 98 
    [40] => 102 
    [45] => 125 
  )

Desired $row_combine Output

Array ( 
   [35] => 100 
   [0] =>  49.99 
   [40] => 102 
   [0] => 98
   [45] => 125 
  )

Actual Output updated

$totalrowcost
Array ( 
  [0] => 100 
  [1] => 49.99 
  [2] => 102 
  [3] => 0 
  [4] => 125 
  ) 

Desired Output updated

$totalrowcost
Array ( 
  [0] => 100 
  [1] => 0 
  [2] => 102 
  [3] => 0 
  [4] => 125 
 )

There are a lot of array functions and when they’re not enough callbacks can usually do what’s needed.

Because the names “rate_row” and “totalrowcost” suggest they are different things, I first thought you might be looking for a way to create a multidimensional array. But going by your “desired” that doesn’t look to be the case.

So what you want is to have the numeric array keys from the original arrays as the numeric keys for the new array, but of the two possible values, use the lower / higher / alternating value of the two??

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.