0

I have an array which contains strings and I need to group them accordingly. Please advise.

Array ( 
  [0] => string1 
  [1] => string1 
  [2] => string2 
  [3] => string2 
  [4] => string3 
  [5] => string1  
      ) 

I need the output as follows:

string1
string2
string3

How can I achieve this?

Sharanya Dutta
  • 3,981
  • 2
  • 17
  • 27
Manoj M
  • 82
  • 6

4 Answers4

1
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

From:http://in3.php.net/array_unique

Dushyant Joshi
  • 3,672
  • 3
  • 28
  • 52
1

First, use array_unique() to get rid of the duplicates, then use sort() to put them in order:

$new_array = array_unique( $orig_array );
sort( $new_array );
print_r( $new_array);

I'm assuming sort because your output is sorted, but that may also be the natural output of removing the duplicates in the example you provided. If you don't want them sorted, just remove the sort().

Nick Coons
  • 3,682
  • 1
  • 19
  • 21
1

array_unique — Removes duplicate values from an array

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Balaji Kandasamy
  • 4,446
  • 10
  • 40
  • 58
1

Use array_unique such as

$new= array_unique($old);
ajon
  • 7,868
  • 11
  • 48
  • 86