Skip to content

Instantly share code, notes, and snippets.

@josephdicdican
Created October 24, 2018 10:24
Show Gist options
  • Save josephdicdican/1fe3895c162eb483e82a72032facc07a to your computer and use it in GitHub Desktop.
Save josephdicdican/1fe3895c162eb483e82a72032facc07a to your computer and use it in GitHub Desktop.
Add/Remove element in reference array from a given array

Scenario:

  1. Item is shared to groups [6,5]
  2. I want to edit item to share to groups [5,4]
    • in result, 6 will be remove and 4 will be added while 5 is as is
<?php

    $shared_groups = [6,5];
    $group_ids = [5,4];

    $new_groups = array_diff($group_ids, $shared_groups);
    $as_is_groups = array_intersect($shared_groups, $group_ids);
    $to_delete_groups = array_diff($shared_groups, $as_is_groups);
    dd(
        'inputs', array($shared_groups, $group_ids),
        'new groups', $new_groups,
        'existing', $as_is_groups,
        'remove', $to_delete_groups
    );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment