Remove all duplicate elements from an array



In this tutorial I am going to show you how to remove all duplicate elements from an array without using array functions in PHP. Below is a simple example of removing duplicate elements from an array without using array function and using array functions.

$array1 = array(0,1,2,3,4,3,5,0,9,6,7,4,8,1);

$array2 = array();
for($i=0;$i<count($array1);$i++) {  
	$array2[$array1[$i]] = isset($array2[$array1[$i]])?$array2[$array1[$i]]+1:1;		
}

$array3 = array();
foreach($array2 as $key => $value) {
	if($value == 1) {
		$array3[] = $key;		
	}
}

print_r($array3);

You will get following in result:

Array ( [0] => 2 [1] => 5 [2] => 9 [3] => 6 [4] => 7 [5] => 8 )

Using Array function in PHP:

$array2 = array_count_values($array1);
$array3 = array();
foreach($array2 as $key => $value) {
	if($value == 1) {
		$array3[] = $key;		
	}
}

print_r($array3);

Hope this tutorial may help you.