Search code examples
phparraysuniquearray-push

How to array_push unique values inside another array


I have two arrays:

$DocumentID = array(document-1, document-2, document-3, document-4,
                    document-5, document-4, document-3, document-2);

$UniqueDocumentID = array();

I want to push the unique objects inside of $documentid array to $UniqueDocumentID array.

I can't use array_unique() as it copies the key of its predecessor array and I want sequential keys inside the $UniqueDocumentID array.


Solution

  • You could foreach() through $DocumentID and check for the current value in $UniqueDocumentID with in_array() and if not present add it. Or use the proper tool:

    $UniqueDocumentID = array_unique($DocumentID);
    

    To your comment about wanting sequential keys:

    $UniqueDocumentID = array_values(array_unique($DocumentID));
    

    The long way around:

    $UniqueDocumentID = array();
    
    foreach($DocumentID as $value) {
        if(!in_array($value, $UniqueDocumentID)) {
            $UniqueDocumentID[] = $value;
        }
    }