An array can stores multiple value in a single variable. There different types of array in PHP such as single dimensional and multi dimensional array. To sorting an array there are in-built function is also available but today we are going to remove duplicate pair from an array without using of in-built functions.This example will help you in many practical case where you have to remove duplicate pairs from your response/array.
Here we are taking an array with some value.As you can see in below code ‘$inputArr2’ has some duplicate pairs such as “D,C” and “C,D”, so basically we are going to find and remove this duplicate pair from an array. So after performing the operation we get final output like this – Array ( [0] => A,B [1] => A,G [2] => B,E [3] => C,D ).
Let’s see the solution –
<?php
$inputArr2 = array("3","A,B", "D,C", "C,D", "B,E", "A,G" );
function getUniqueLists($frndLists){
$unArr1 = array();
$unArr2 = array();
$opArr = array();
for($j = 0; $j < count($frndLists); $j ++) {
for($i = 0; $i < count($frndLists)-1; $i ++){
if($frndLists[$i] > $frndLists[$i+1]) {
$temp = $frndLists[$i+1];
$frndLists[$i+1]=$frndLists[$i];
$frndLists[$i]=$temp;
}
}
}
foreach($frndLists as $fnd_key => $fnd_val){
$is_exist =0;
$expArr = explode(",", $fnd_val);
if(count($expArr) == 2){
if(is_string($expArr[0]) && is_string($expArr[1])){
if(in_array($expArr[0], $unArr1) or in_array($expArr[0], $unArr2)){
$is_exist++;
}
if(in_array($expArr[1], $unArr1) or in_array($expArr[1], $unArr2)){
$is_exist++;
}
if($is_exist != 2){
array_push($unArr1, $expArr[0]);
array_push($unArr2, $expArr[1]);
}
}
}
}
for($u =0; $u < count($unArr1); $u++){
$new_arr = $unArr1[$u].",".$unArr2[$u];
array_push($opArr, $new_arr);
}
return $opArr;
}
$output = getUniqueLists($inputArr2);
print_r($output);
?>
Output-
Array ( [0] => A,B [1] => A,G [2] => B,E [3] => C,D )