March 29, 2012

DISTINCT for foreach

Question by Dirk Fograust

<?php

$array = array('aaa', 'bbb', 'aaa', 'ccc', 'ddd', 'ccc', 'eee');

foreach($array as $a){
   echo $a;
}

Is possible use some like DISTINCT for foreach? I would like show each values only one, without repeat. How is the best way for this?

http://codepad.org/FZQNEBeK

Answer by tereško

Actually array_unique() gets pretty bad when you have large arrays. You would be better off with $uniques = array_flip(array_flip($array)).

Answer by Starx

Use array_unique()

$array = array('aaa', 'bbb', 'aaa', 'ccc', 'ddd', 'ccc', 'eee');
$result = array_unique($array);
print_r($result);

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!