Compare 2 arrays and preserve the row number
The stock managing system needs to preserve the order of row number (orderline) when you do the returns, but don't send the items that are not refunded.


If that's the requirement, then you should store the row number in the database at the time that the order is placed.  The problems that you are having come from trying to rebuild this information later.  If you want something to be persistent, store it.  You would only want to build it on the fly if you want it to change with other changes.  But in this case, that's explicitly not what you want.  

This would be easier to answer if you included more code.  For example, how do you write to your database?  I'm suggesting a change in that.  How do you read from your database?  I'm suggesting that you read another column.  How do you build your data structures?  They might change as well.  

In the following:


    foreach ($creditmemo-&gt;getAllItems() as $key =&gt; $item) {

            //if item is inside a grouped element, i.e 2-7 put the orderline at 2 then the next one at 8 
            foreach($result as $val){
                if(strpos($val,"-")){
                    $piece = explode("-", $val);
                    if(($piece[0]) == $i){
                        $orderline = $piece[0];
                        $i = $piece[1] + 1; 

                    }
                }
            }
//if item is single
            if(in_array($i, $result)){ 
                $orderline = $i+1; 
                $i++;
            }               
            else{ 
                $orderline = $i; 
            }



You could just say 

    foreach ($creditmemo-&gt;getAllItems as $item) {
        $orderline = $item-&gt;getOrderLine();


Of course, this adds additional work when inserting into the database, but since you don't provide that, we can't help you make changes to it.  Nor can we help with the changes to the $item object, as we don't see how it's built.