ssuhat
ssuhat

Reputation: 7656

PHP array push to array but keep existing sequence

I have this 2 array:

$array1 = [3,6,5];
$array2 = [1,2,3,4,5,6];

I want to achieve this:

$newArray = [3,6,5,1,2,4];

so it keep the sequence and append the missing value on $array1.

    foreach($array1 as $data){
        if(!in_array($data, $array2)){
            array_push($array2, $data);
        }
    }

I try above code but what i got is my array become double.

Any solution?

Upvotes: 0

Views: 239

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 78994

To stay with your existing approach, you need to change your logic:

foreach($array2 as $data){
    if(!in_array($data, $array1)){
        array_push($array1, $data);
        //or
        //$array1[] = $data;
    }
}

Upvotes: 0

Pezhvak
Pezhvak

Reputation: 10858

try this:

$array1 = [3,6,5];
$array2 = [1,2,3,4,5,6];
$diff = array_diff($array2, $array1);
$newArray = array_merge($array1, $diff);

hope it helps..

Upvotes: 0

Kushan
Kushan

Reputation: 10695

Like this,

$newArray = array_unique(array_merge($array1 ,$array2));

This array_merge() function use for merge one or more arrays into one array and array_unique() function removes duplicate values from an array.

Upvotes: 3

Related Questions