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?
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
From:http://in3.php.net/array_unique
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()
.
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);
?>
Use array_unique such as
$new= array_unique($old);