Please, read the manual. array_unique
doesn't reset the array keys. Besides, a for
loop is all well and good, but foreach
is a language construct better suited to deal with arrays (and objects, for that matter).
That said, the fastest way to reset the array keys after array_unique
has been applied is to sort
the array:
$a = array( 'Pritesh','Pritesh','Nilesh' );
$b = array_unique($a);
sort($b);
var_dump($b);
This results in:
array(2) {
[0]=>
string(6) "Nilesh"
[1]=>
string(7) "Pritesh"
}
Which is suitable for both for
and foreach
.
Edit:
As is often the case in programming TMTOWTDI (There's more than one way to do it). Here's a couple of approaches, ranging from valid to absurd:
Quick:
foreach($uniques as $unique) echo '<option value="', $unique, '">', $unique,'</option>';
Yes those are comma's, comma's + echo is actually faster (~20-30%) than concatenation
When to use: whenever you feel like it, it doesn't change the $uniques
array (so it's still inconcistently indexed), but it's quick and easy to read.
Fix $uniques
indexing:
sort($uniques);
foreach($uniques as $unique) echo '';//same deal
The difference with the previous version is that you can replace foreach
with for
here, too, and that the $uniques
array will be properly indexed again. The order of the elements may have changed.
If the order of the elements is important, and you want a neatly indexed array, use:
$uniques = array_values($uniques);//as Shankar Damodaran suggested
Use when your use-case fits the very specific and unlikely scenario described above.
or, and things are getting absurd from here on end:
function keepOrder($a, $b)
{
return 0;
}
usort($uniques, 'keepOrder);
Use: never
Since we are taking it rather far in terms of over-engineering a solution, let's take it to the extend where the solution becomes a problem all over again (Warning, the following code may cause your eyes to bleed):
//get the highest key in array, add 1
$max = max(array_keys($uniques)) + 1;
for($i=0;$i<$max;++$i) if (isset($uniques[$i])) echo $unique;
I've deliberately made the code above harder to read, to avoid anyone using it.
When to use: use when you are either clinically insane, or want to see a co-worker being taken away in a straitjacket, shouting "The horror, the horror".
Seriously: don't use it.