Scorpyon
Scorpyon

Reputation: 236

Using PHP remove duplicates from an array without using any in- built functions?

Lets say I have an array as follows :

$sampArray = array (1,4,2,1,6,4,9,7,2,9)

I want to remove all the duplicates from this array, so the result should be as follows:

$resultArray = array(1,4,2,6,9,7)

But here is the catch!!! I don't want to use any PHP in built functions like array_unique().

How would you do it ? :)

Upvotes: 4

Views: 27891

Answers (7)

Nitin Kumar
Nitin Kumar

Reputation: 1

$sampArray = array (1,4,2,1,6,4,9,7,2,9);
 $resultArray = array();
 foreach ($sampArray as $key => $value){
        $counter = true;

        for ($i = 0; $i < $key; $i++) {
            if($value == $sampArray[$i]) {
                $counter = false;
                 break;
              }
          }

      if($counter)
         $resultArray[]=$value;
 }
      
      
print_r($resultArray);

Upvotes: 0

Trimbak Gopalghare
Trimbak Gopalghare

Reputation: 89

<?php
$inputArray = array(1, 4, 2, 1, 6, 4, 9, 7, 2, 9);
$outputArray = array();

foreach ($inputArray as $val){
 if(!in_array($val,$outputArray)){
  $outputArray[] = $val;
 }
}
print_r($outputArray);

Upvotes: 2

seymar
seymar

Reputation: 4063

A serious (working) answer:

$inputArray = array(1, 4, 2, 1, 6, 4, 9, 7, 2, 9);
$outputArray = array();

foreach($inputArray as $inputArrayItem) {
    foreach($outputArray as $outputArrayItem) {
        if($inputArrayItem == $outputArrayItem) {
            continue 2;
        }
    }
    $outputArray[] = $inputArrayItem;
}
print_r($outputArray);

Upvotes: 4

hakre
hakre

Reputation: 198124

Edit2: The versions below use a hashmap to determine if a value already exists. In case this is not possible, here is another variant that safely works with all PHP values and does a strict comparison (Demo):

$array = array (1,4,2,1,6,4,9,7,2,9);

$unique = function($a)
{
    $u = array();    
    foreach($a as $v)
    {
        foreach($u as $vu)
            if ($vu===$v) continue 2
        ;
        $u[] = $v;
    }
    return $u;
};

var_dump($unique($array)); # array(1,4,2,6,9,7)

Edit: Same version as below, but w/o build in functions, only language constructs (Demo):

$array = array (1,4,2,1,6,4,9,7,2,9);
$unique = array();
foreach($array as $v)
  isset($k[$v]) || ($k[$v]=1) && $unique[] = $v; 

var_dump($unique); # array(1,4,2,6,9,7)

And in case you don't want to have the temporary arrays spread around, here is a variant with an anonymous function:

$array = array (1,4,2,1,6,4,9,7,2,9);

$unique = function($a) /* similar as above but more expressive ...                   ... you have been warned: */ {for($v=reset($a);$v&&(isset($k[$v])||($k[$v]=1)&&$u[]=$v);$v=next($a));return$u;};

var_dump($unique($array)); # array(1,4,2,6,9,7)

First was reading that you don't want to use array_unique or similar functions (array_intersect etc.), so this was just a start, maybe it's still of som use:

You can use array_flip PHP Manual in combination with array_keys PHP Manual for your array of integers (Demo):

$array = array (1,4,2,1,6,4,9,7,2,9);

$array = array_keys(array_flip($array));

var_dump($array); # array(1,4,2,6,9,7)

As keys can only exist once in a PHP array and array_flip retains the order, you will get your result. As those are build in functions it's pretty fast and there is not much to iterate over to get the job done.

Upvotes: 2

Artefacto
Artefacto

Reputation: 97835

This depends on the operations you have available.

  • If all you have to detect duplicates is a function that takes two elements and tells if they are equal (one example will be the == operation in PHP), then you must compare every new element with all the non-duplicates you have found before. The solution will be quadratic, in the worst case (there are no duplicates), you need to do (1/2)(n*(n+1)) comparisons. If your arrays can have any kind of value, this is more or less the only solution available (see below).

  • If you have a total order for your values, you can sort the array (n*log(n)) and then eliminate consecutive duplicates (linear). Note that you cannot use the <, >, etc. operators from PHP, they do not introduce a total order. Unfortunately, array_unique does this, and it can fail because of that.

  • If you have a hash function that you can apply to your values, than you can do it in average linear time with a hash table (which is the data structure behind an array). See tandu's answer.

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191779

Here is a simple O(n)-time solution:

$uniqueme = array();
foreach ($array as $key => $value) {
   $uniqueme[$value] = $key;
}
$final = array();
foreach ($uniqueme as $key => $value) {
   $final[] = $key;
}

You cannot have duplicate keys, and this will retain the order.

Upvotes: 10

Toby Allen
Toby Allen

Reputation: 11211

You could use an intermediate array into which you add each item in turn. prior to adding the item you could check if it already exists by looping through the new array.

Upvotes: 0

Related Questions