Moe Joe
Moe Joe

Reputation: 75

merging two arrays in a specific way

I want to combine two arrays with almost same values. I always want to insert an array element into the combined array if it exists. For:

$b = array("a","a","b","a","a","x")

$a = array("a","a","b","x","a","a")

I want to have the output:

$ab = array ("a","a","b","x","a","a","x");

The function array_merge or array_combine does not work.

Upvotes: 1

Views: 53

Answers (2)

Rasclatt
Rasclatt

Reputation: 12505

I would maybe try using array_splice(). You'd have to try this on different arrays to see if it works in all scenarios:

<?php
$b = array("a","a","b","a","a","x");
$a = array("a","a","b","x","a","a");

function iterateToEven(&$a,&$b)
    {
        $c  =   count($a);
        for($i = 0; $i < $c; $i++) {
            if(isset($a[$i])){
                if(isset($b[$i])) {
                    if($a[$i] == $b[$i])
                        continue;
                    else {
                        if(isset($b[$i+1]) && ($b[$i+1] == $a[$i]))
                            array_splice($a,$i,0,$b[$i]);
                        elseif(isset($a[$i+1]) && ($a[$i+1] == $b[$i]))
                            array_splice($b,$i,0,$a[$i]);
                        else
                            array_splice($a,$i,0,$b[$i]);
                    }
                }
            }
        }

        if(end($a) != end($b)) {
            if(count($a) == count($b))
                iterateToEven($a,$b);
        }

        return (count($a) > count($b))? $a : $b;
    }

$d  =   iterateToEven($a,$b);

print_r($d);

Gives the output:

Array
(
    [0] => a
    [1] => a
    [2] => b
    [3] => x
    [4] => a
    [5] => a
    [6] => x
)

One caveat, this method will modify both the $a & $b arrays in the process of doing this function so if you wanted to keep both $a and $b intact, you could wrap the function application inside another function and return $d.

Upvotes: 1

Sachith Muhandiram
Sachith Muhandiram

Reputation: 2972

I used following code

$b = array("a","a","b","a","a","x");
$a = array("a","a","b","x","a","a");
$list = []; //empty array

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

       if ($i== $j) {
           $list[] = $a[$i]; //if values are equal, list[] gets array a value
       }
       else{
        $list[] = $b[$j];
       }
   }
}

return $list;

Result is : ["a","a","b","x","a","a"]

Upvotes: 0

Related Questions