d'art
d'art

Reputation: 87

How to get unique array in php

I'v an array like this:

Array([0] => 1,[1] => 2,[2] => 3,[3] => 3,[4] => 4,[5] => 5,[6] => 5,[7] => 6,[8] => 6,[9] => 6,[10] => 7,[11] => 8,[12] => 8,[13] => 8,[14] => 8,[15] => 9,[16] => 9,[17] => 9,[18] => 9,[19] => 9)

but the results I want like this:

Array([0] => 1,[1] => 2,[3] => 3,[4] => 4,[6] => 5,[9] => 6,[10] => 7,[14] => 8,[19] => 9)

This not only eliminates the value of the same array, but the same value that appears to be the value of the index / key of the last of the same value. anyone can help me?

Upvotes: 1

Views: 97

Answers (6)

d'art
d'art

Reputation: 87

ok, I've got the answer I want, thank you to all who have tried to help me.

$str = Array('0' => 1,'1' => 2,'2' => 3,'3' => 3,'4' => 4,'5' => 5,'6' => 5,'7' => 6,'8' => 6,'9' => 6,'10' => 7,'11' => 8,'12' => 8,'13' => 8,'14' => 8,'15' => 9,'16' => 9,'17' => 9,'18' => 9,'19' => 9);

$flag = 0;
foreach($str as $key=>$value)
{
   if($flag == $value)
   {
      unset($str[$key-1]);
   }
   $flag = $value;
 }
 echo "<pre>";
 print_r($str);

Upvotes: 0

Iffi
Iffi

Reputation: 588

Use the build in array function.

array_unique();

give you the expected the results. Check the link

Upvotes: 0

Priyank
Priyank

Reputation: 3868

array_unique

<?php $arr=Array("[0]" => 1,"[1]" => 2,"[2]" => 3,"[3]" => 3,"[4]" => 4,"[5]" => 5,"[6]" => 5,"[7]" => 6,"[8]" => 6,"[9]" => 6,"[10]" => 7,"[11]" => 8,"[12]" => 8,"[13]" => 8,"[14]" => 8,"[15]" => 9,"[16]" => 9,"[17]" => 9,"[18]" => 9,"[19]" => 9);
var_dump($arr);
$newarr=array_unique($arr);
var_dump($newarr);
?>

Upvotes: 0

Sharma Vikram
Sharma Vikram

Reputation: 2470

array_unique() function through you can get a unique value of array.

<?php

$data=Array(1,2,3,3,4,5,5,6,6,6,7,8,8,8,8,9,9,9,9);
echo '<pre>';
print_r($data);
$ans=array_unique($data);
print_r($ans);
echo '</pre>';
?>

Upvotes: 0

Girish
Girish

Reputation: 12117

You can use array manipulation function

array_unique($arr);

Upvotes: 0

Manwal
Manwal

Reputation: 23816

array_unique()

Takes an input array and returns a new array without duplicate values.

Example:

array_unique($your_array);

Upvotes: 1

Related Questions