-5

I have array A :

Input:

A ={2,3,2,{1},3,2,{0},3,2,0,11,7,9,{2}}

I want output to be Array B

Output:

B={0,1,2,3,7,9,11}

How can i remove the duplicate values and sort them ascending with PHP?

rvandoni
  • 3,297
  • 4
  • 32
  • 46
user3636123
  • 41
  • 2
  • 7

3 Answers3

3

if you have:

$a = array(2,3,2,1,3,2,0,3,2,0,11,7,9,2);

you can use array_unique() to remove duplicates:

$a = array_unique($a);

and then use asort() to sort the array values:

asort($a);
rvandoni
  • 3,297
  • 4
  • 32
  • 46
  • 1
    asort sorts in place and returns a boolean of success(in practice always true, since a failure is a fatal error). Assigning a to the result of `asort` will always leave you with `true` in `$a` and not the sorted array. – scragar Sep 11 '14 at 10:04
  • @scagar: you're right, I fix it :) – rvandoni Sep 11 '14 at 10:05
2

//Try this out...

$array = array(2,3,2,(1),3,2,(0),3,2,0,11,7,9,(2));
$array_u = array_unique($array);
sort($array_u);
print_r($array_u);

Sample output

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 7
    [5] => 9
    [6] => 11
)
Sujit Agarwal
  • 12,348
  • 11
  • 48
  • 79
0

First step: flattern

function flatten(array $array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}

then using asort and array_unique you can remove duplicates and sort ascendent.

$result = array_unique(flattern($array));
asort($result);

Sources: How to Flatten a Multidimensional Array?

Community
  • 1
  • 1
ProGM
  • 6,949
  • 4
  • 33
  • 52