0

I have the following array

$ar = array ( 1,2,3,4,5,3,6,7,...)

i do a foreach to display elements like

$i = 0
foreach ($ar as $tab){

echo $tab[i];

$i++
}

I dont want to display twice the same value like 3. i just want 1 2 3 4 5 6 7...

0

3 Answers 3

4

You can use array_unique to get the unique set of values from your array before iterating over it:

$arr = array(1,2,3,4,5,3,6,7);
foreach (array_unique($arr) as $tab)
{
  // ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

try array_unique

Comments

0

You may use flip-flip-merge technique which is faster than array_unique()

$ar = array(1,2,3,4,5,3,6,7);
$ar = array_merge(array_flip(array_flip($ar)));

You may read about it here http://thebatesreport.com/blog/?p=9

5 Comments

That article is more than 4 years old.
and? I tested it with PHP 5.3 Results >>> 0.0122 (flip-flip-merge) 0.514 (array_unique)
linux 2.6.32-5-686-bigmem, php 5.3.2: 0m19.412s (flipper) vs. 0m19.123s (unique) (a few thousand iterations of course)
It does seem terribly dependent on the actual data, whether there are doubles, etc.
thank you guys, your solution ( array_unique) does the job. But my array is more complex than the exemple i gave. Am going to see how to adapt !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.