This question already has an answer here:
I have this array:
$number = array("a", "b", "b", "c", "a", "b", "c", "b", "c");
Now I want to get all unique values. Means the result should be:
$result = array("a", "b", "c");
Now I know that this can easily be solved with array_unique()
. But I want to write my own little implementation of array_unique()
just using a for loop, unset()
and array_values()
.
</div>
use array_unique()
<?php
$number=array("a","b","b","c","a","b","c","b","c");
$unique_array=array_unique($number);
print_r($unique_array);
?>
//second posibility
<?php
$number=array("a","b","b","c","a","b","c","b","c");
$unique_array=[];
foreach($number as $val)
{
$unique_array[$val]=$val;
}
print_r(array_values($unique_array));
?>
//Third posibility with for,unset,array_value
<?php
$number=array("a","b","b","c","a","b","c","b","c");
$count=count($number);
for($i=0;$i<$count;$i++)
{
if($i<count($number))
{
for($j=$i+1;$j<$count;$j++)
{
if($number[$i]==$number[$j])
{
unset($number[$j]);
}
}
}
}
$number=array_values($number);
print_r($number);
?>
expected result is
Array ( [0] => a [1] => b [2] => c )
Something like this maybe? Here we are looping through and array starting in one for
from the position 0 and in the other from 1. We compare the $i
position with all the others in array and if it finds two same it removes the second one.
<?php
$number = array("a", "b", "b", "c", "a", "b", "c", "b", "c");
$count = count($number);
for($i = 0; $i < $count; $i++) {
for($j = $i+1; $j < $count; $j++) {
if(isset($number[$j]) && isset($number[$i]) && $number[$i] == $number[$j]) {
unset($number[$j]);
}
}
}
print_r($number);