-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?

1
  • Use array_unique() method Commented Sep 11, 2014 at 10:01

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@scagar: you're right, I fix it :)
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
)

3 Comments

Op wanted ascending sort so asort() is better ;)
php.net/manual/en/function.sort.php By default sort works as asort() :)
true :) you're right
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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.