-1

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.

3
  • 2
    $UniqueDocumentID = array_unique($DocumentID);??? Commented Oct 10, 2016 at 20:59
  • First start by creating a valid array in $DocumentID Commented Oct 10, 2016 at 21:00
  • I can't use array_unique as it copies the key of its predecessor array and I want sequential keys inside the $UniqueDocumentID array, that is why I need to push objects into $UniqueDocumentID array to keep them in a sequence of ascending order of key. Commented Oct 10, 2016 at 21:01

1 Answer 1

3

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.