1

I have 2 arrays fruit

      Array(
        [0]=>'Apple',
        [1]=>'orange',
        [2]=>'guava'
        )

and second array is Allfruits

    Array(
    [0]=>'Strawberry',
    [1]=>'Manggo',
    [2]=>'durian',
    [3]=>'Apple',
    [4]=>'guava')

And then an empty array call $data

My question is how to insert members of Allfruits when it not exists in fruit array?

So with this example, i want the result is all fruit except Apple and guava inside data array any sugestion?

2
  • array_diff Commented Oct 13, 2020 at 6:02
  • What result do you need? @Bayu Zangetsu Commented Oct 13, 2020 at 6:04

3 Answers 3

2

Here is a simple way of doing that

$items_to_add = array_diff($array_fruit, $array_all_fruit);

$exclude_existing = array_diff($array_all_fruit, $array_fruit);

$new_array = array_merge($items_to_add, $exclude_existing);
Sign up to request clarification or add additional context in comments.

Comments

0

By using below function, you can merge 2arrays without duplicate

function mergeArrayIfNotExist($childArray, $parentArray) {
    for ($i = 0; $i < sizeof($childArray), $i++) {
        if (!in_array($childArray[$i], $parentArray)) {
            array_push($parentArray, $childArray[$i]);
        }
    }
    return $parentArray;
}

Comments

0

Just run a loop and search the value in the $data array. If it is in the array then get it's index by using array_search function and unset the value, otherwise add the value in $data array. Finally re-index the array if you need.

$check = ['Apple','orange','guava'];
$data = ['Strawberry','Manggo','durian','Apple','guava'];

foreach ($check as $key => $value) {
    if(( $index = array_search( $value, $data )) !== false ){
        unset( $data[$index] ); 
    }else{
        $data[] = $value;
    }
}
$data = array_values( $data ); //for re-indexing the array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.