0

I have a array which consist of further sub arrays like

    Array
(
    [0] => MM
    [1] => CM
    [2] => Inch
)
Array
(
    [0] => MM
    [1] => CM
    [2] => Inch
)

Since both arrays have same elements so i try to fetch one from that.I try array_unique(),merge function but didn't succeed.I can remove one array by using foreach loop but i want to know that if it is possible by single statement, like some bulitin function or one line code not more than that.Hopes got my point.I my trying to reduce my code

Mahmood Rehman
  • 4,303
  • 7
  • 39
  • 76

3 Answers3

1

If I get your question, you are trying to remove duplicate subarrays. Try this

$input = array_map("unserialize", array_unique(array_map("serialize", $input)));

array_unique removes duplicates from an array.

array_map takes 2 arguments

array_map ( callable $callback , array $arr1 [, array $... ] )

it recursively runs the callback on the array

Basically the code serializes the array's content (each sub-array in this case), removes the duplicates then unserialize the content to recreate the original array

More here: How to remove duplicate values from an array in PHP

Community
  • 1
  • 1
Joshua Kissoon
  • 3,269
  • 6
  • 32
  • 58
0

use like below for only one statement

  <?php
    $arr1 = array('MM','CM','Inch');
    $arr2 = array('MM','CM','Inch');
    $array = array_values(array_unique(array_merge($arr1,$arr2)));

echo "<pre]>";
print_r($array);
exit;

?>

OUTPUT

Array
(
    [0] => MM
    [1] => CM
    [2] => Inch
)
liyakat
  • 11,825
  • 2
  • 40
  • 46
0

Before that.. I'm edit a little of your code. I use code like this ::

    <?php
    $a = Array(
        Array(
            0 => MM,
            1 => CM,
            2 => Inch
        ),
        Array(
            0 => MM,
            1 => CM,
            2 => Inch
        )
    );

    print_r($a);
    echo "<br/><br/><br/>";

    print_r(array_unique($a));
    ?>

And result from my code ::

    Array ( [0] => Array ( [0] => MM [1] => CM [2] => Inch ) [1] => Array ( [0] => MM [1] => CM [2] => Inch ) ) 


    Array ( [0] => Array ( [0] => MM [1] => CM [2] => Inch ) )

Hope it will help. Regards.

Tri Asmoro
  • 51
  • 7