Related
How can I remove duplicate values from an array in PHP?
Use array_unique().
Example:
$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
Use array_values(array_unique($array));
array_unique: for unique array
array_values: for reindexing
//Find duplicates
$arr = array(
'unique',
'duplicate',
'distinct',
'justone',
'three3',
'duplicate',
'three3',
'three3',
'onlyone'
);
$unique = array_unique($arr);
$dupes = array_diff_key( $arr, $unique );
// array( 5=>'duplicate', 6=>'three3' 7=>'three3' )
// count duplicates
array_count_values($dupes); // array( 'duplicate'=>1, 'three3'=>2 )
$result = array();
foreach ($array as $key => $value){
if(!in_array($value, $result))
$result[$key]=$value;
}
The only thing which worked for me is:
$array = array_unique($array, SORT_REGULAR);
Edit : SORT_REGULAR keeps the same order of the original array.
sometimes array_unique() is not the way,
if you want get unique AND duplicated items...
$unique=array("","A1","","A2","","A1","");
$duplicated=array();
foreach($unique as $k=>$v) {
if( ($kt=array_search($v,$unique))!==false and $k!=$kt )
{ unset($unique[$kt]); $duplicated[]=$v; }
}
sort($unique); // optional
sort($duplicated); // optional
results on
array ( 0 => '', 1 => 'A1', 2 => 'A2', ) /* $unique */
array ( 0 => '', 1 => '', 2 => '', 3 => 'A1', ) /* $duplicated */
We can easily use arrar_unique($array); to remove duplicate elements
But the problem in this method is that the index of the elements are not in order, will cause problems if used somewhere else later.
Use
$arr = array_unique($arr);
$arr = array_values($arr);
print_r($arr);
Or
$arr = array_flip($arr);
$arr = array_flip($arr);
$arr = array_values($arr);
print_r($arr);
The first flip , flips the key value pair thus combines the elements with similar key(that was originally the value).
2nd flip to revert all the key value pairs. Finally array_value() sets each value with key starting from 0.
Note: Not to be used in associative array with predefined key value pairs
$a = array(1, 2, 3, 4);
$b = array(1, 6, 5, 2, 9);
$c = array_merge($a, $b);
$unique = array_keys(array_flip($c));
print_r($unique);
We can create such type of array to use this last value will be updated into column or key value and we will get unique value from the array...
$array = array (1,3,4,2,1,7,4,9,7,5,9);
$data=array();
foreach($array as $value ){
$data[$value]= $value;
}
array_keys($data);
OR
array_values($data);
explode(",", implode(",", array_unique(explode(",", $YOUR_ARRAY))));
This will take care of key associations and serialize the keys for the resulting new array :-)
Depending on the size of your array, I have found
$array = array_values( array_flip( array_flip( $array ) ) );
can be faster than array_unique.
There can be multiple ways to do these, which are as follows
//first method
$filter = array_map("unserialize", array_unique(array_map("serialize", $arr)));
//second method
$array = array_unique($arr, SORT_REGULAR);
If you concern in performance and have simple array, use:
array_keys(array_flip($array));
It's many times faster than array_unique.
This example is just an alternative.
<?php
$numbers = [1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,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ique_numbers)); //// Array is now 1,3,4,5,6,2,7, ....
That's a great way to do it. Might want to make sure its output is back an array again. Now you're only showing the last unique value.
Try this:
$arrDuplicate = array ("","",1,3,"",5);
foreach (array_unique($arrDuplicate) as $v){
if($v != "") { $arrRemoved[] = $v; }
}
print_r ($arrRemoved);
if (#!in_array($classified->category,$arr)){
$arr[] = $classified->category;
?>
<?php } endwhile; wp_reset_query(); ?>
first time check value in array and found same value ignore it
Remove duplicate values from an associative array in PHP.
$arrDup = Array ('0' => 'aaa-aaa' , 'SKU' => 'aaa-aaa' , '1' => '12/1/1' , 'date' => '12/1/1' , '2' => '1.15' , 'cost' => '1.15' );
foreach($arrDup as $k => $v){
if(!( isset ($hold[$v])))
$hold[$v]=1;
else
unset($arrDup[$k]);
}
Array ( [0] => aaa-aaa [1] => 12/1/1 [2] => 1.15 )
$arrDuplicate = array ("","",1,3,"",5);
foreach(array_unique($arrDuplicate) as $v){
if($v != "" ){$arrRemoved = $v; }}
print_r($arrRemoved);
try this short & sweet code -
$array = array (1,4,2,1,7,4,9,7,5,9);
$unique = array();
foreach($array as $v){
isset($k[$v]) || ($k[$v]=1) && $unique[] = $v;
}
var_dump($unique);
Output -
array(6) {
[0]=>
int(1)
[1]=>
int(4)
[2]=>
int(2)
[3]=>
int(7)
[4]=>
int(9)
[5]=>
int(5)
}
<?php
$arr1 = [1,1,2,3,4,5,6,3,1,3,5,3,20];
print_r(arr_unique($arr1));
function arr_unique($arr) {
sort($arr);
$curr = $arr[0];
$uni_arr[] = $arr[0];
for($i=0; $i<count($arr);$i++){
if($curr != $arr[$i]) {
$uni_arr[] = $arr[$i];
$curr = $arr[$i];
}
}
return $uni_arr;
}
Here I've created a second empty array and used for loop with the first array which is having duplicates. It will run as many time as the count of the first array. Then compared with the position of the array with the first array and matched that it has this item already or not by using in_array. If not then it'll add that item to second array with array_push.
$a = array(1,2,3,1,3,4,5);
$count = count($a);
$b = [];
for($i=0; $i<$count; $i++){
if(!in_array($a[$i], $b)){
array_push($b, $a[$i]);
}
}
print_r ($b);
It can be done through function I made three function duplicate returns the values which are duplicate in array.
Second function single return only those values which are single mean not repeated in array and third and full function return all values but not duplicated if any value is duplicated it convert it to single;
function duplicate($arr) {
$duplicate;
$count = array_count_values($arr);
foreach($arr as $key => $value) {
if ($count[$value] > 1) {
$duplicate[$value] = $value;
}
}
return $duplicate;
}
function single($arr) {
$single;
$count = array_count_values($arr);
foreach($arr as $key => $value) {
if ($count[$value] == 1) {
$single[$value] = $value;
}
}
return $single;
}
function full($arr, $arry) {
$full = $arr + $arry;
sort($full);
return $full;
}
An alternative for array_unique() function..
Using Brute force algorithm
//[1] This our array with duplicated items
$matches = ["jorge","melvin","chelsy","melvin","jorge","smith"];
//[2] Container for the new array without any duplicated items
$arr = [];
//[3] get the length of the duplicated array and set it to the var len to be use for for loop
$len = count($matches);
//[4] If matches array key($i) current loop Iteration is not available in
//[4] the array $arr then push the current iteration key value of the matches[$i]
//[4] to the array arr.
for($i=0;$i
if(array_search($matches[$i], $arr) === false){
array_push($arr,$matches[$i]);
}
}
//print the array $arr.
print_r($arr);
//Result: Array
(
[0] => jorge
[1] => melvin
[2] => chelsy
[3] => smith
)
<?php
$a=array("1"=>"302","2"=>"302","3"=>"276","4"=>"301","5"=>"302");
print_r(array_values(array_unique($a)));
?>//`output -> Array ( [0] => 302 [1] => 276 [2] => 301 )`
I have done this without using any function.
$arr = array("1", "2", "3", "4", "5", "4", "2", "1");
$len = count($arr);
for ($i = 0; $i < $len; $i++) {
$temp = $arr[$i];
$j = $i;
for ($k = 0; $k < $len; $k++) {
if ($k != $j) {
if ($temp == $arr[$k]) {
echo $temp."<br>";
$arr[$k]=" ";
}
}
}
}
for ($i = 0; $i < $len; $i++) {
echo $arr[$i] . " <br><br>";
}
$array = array("a" => "moon", "star", "b" => "moon", "star", "sky");
// Deleting the duplicate items
$result = array_unique($array);
print_r($result);
ref : Demo
$arr1 = [1,2,3];
$arr2 = [1,2,3,4];
$arr3 = [1,2,3,4,5];
echo max( count($arr1), count($arr2), count($arr3) ); // returns 5
with max I do get the count, but don't know which array is larger. How do I get the larger array's reference ($arr3 in this case)?
You should use multidimensional array to store your all arrays then, loop through the multidimensional array and find your largest array,
$lgArraySize = 0; // used for comparing the size of array
$lgArray = array(); // used to store reference of largest array
foreach($arraylist as $array) {
if(count($array) > $largeArraySize) {
$lgArray = &$array;
$lgArraySize = count($array);
}
}
print_r($largeArray);
Here is the one liner code.(that you want)
function findMax( $row ){
return count($row);
}
$maxArrayPos = array_search(max( array_map("findMax", $multi )), array_map("findMax", $multi ));
print_r($multi[$maxArrayPos]);
You can make this as one liner.
It's better to use indexes for such arrays, so that traversal is easy.
You can get reference to the larger array as follows -
$arr;
$arr[0] = [6,2,1,12,32,11];
$arr[1] = [1,2,3,4];
$arr[2] = [1,2,3,4,4,4,1,1,1,1];
$count = -1;//will hold max count
$big;//larger array will be stored here
foreach ($arr as $key => $value) {
$curCount = count($arr[$key]);//curCount holds current array size
//checking for biggest array count
if($curCount>$count){
$count = $curCount;
$big = &$arr[$key];
}
}
var_dump($big);
Maybe the logic is too bulky though!
Is this what you need?
$arr1 = [1,2,3];
$arr2 = [1,2,3,4];
$arr3 = [1,2,3,4,5];
$countmax = [
"arr1" => $arr1,
"arr2" => $arr2,
"arr3" => $arr3,
];
$value = max($countmax);
print_r($value);
Oputput:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Try this :
function laregr(){
$numargs = func_num_args();
$large_array = array();
if($numargs){
$arg_list = func_get_args();
$max = 0;
foreach($arg_list as $arg){
if(is_array($arg)){
$big = count($arg);
if($big >= $max ){
$max = $big;
$large_array = $arg;
}
}
}
}
return $large_array;
}
$arr1 = [1,2,3,4,5,6];
$arr2 = [1,2,3,4,5];
$arr4 = [1,2,3,4, 5,6,7];
$max_array = laregr($arr1, $arr2, $arr4); // large($arr1, ...)
print_r($max_array);
You may like to store all arrays inside an array and would like to do a foreach I think.
function max_length($array) {
$max = 0;
foreach($array as $child) {
if(count($child) > $max) {
$max = count($child);
}
}
return $max;
}
check this why it is better approach .
Please help me to translate this pseudo-code to real php code:
foreach ($arr as $k => $v)
if ( THIS IS NOT THE LAST ELEMENT IN THE ARRAY)
doSomething();
Edit: the array may have numerical or string keys
you can use PHP's end()
$array = array('a' => 1,'b' => 2,'c' => 3);
$lastElement = end($array);
foreach($array as $k => $v) {
echo $v . '<br/>';
if($v == $lastElement) {
// 'you can do something here as this condition states it just entered last element of an array';
}
}
Update1
as pointed out by #Mijoja the above could will have problem if you have same value multiple times in array. below is the fix for it.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
//point to end of the array
end($array);
//fetch key of the last element of the array.
$lastElementKey = key($array);
//iterate the array
foreach($array as $k => $v) {
if($k == $lastElementKey) {
//during array iteration this condition states the last element.
}
}
Update2
I found solution by #onteria_ to be better then what i have answered since it does not modify arrays internal pointer, i am updating the answer to match his answer.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
// Get array keys
$arrayKeys = array_keys($array);
// Fetch last array key
$lastArrayKey = array_pop($arrayKeys);
//iterate array
foreach($array as $k => $v) {
if($k == $lastArrayKey) {
//during array iteration this condition states the last element.
}
}
Thank you #onteria_
Update3
As pointed by #CGundlach PHP 7.3 introduced array_key_last which seems much better option if you are using PHP >= 7.3
$array = array('a' => 1,'b' => 2,'c' => 3);
$lastKey = array_key_last($array);
foreach($array as $k => $v) {
echo $v . '<br/>';
if($k == $lastKey) {
// 'you can do something here as this condition states it just entered last element of an array';
}
}
This always does the trick for me
foreach($array as $key => $value) {
if (end(array_keys($array)) == $key)
// Last key reached
}
Edit 30/04/15
$last_key = end(array_keys($array));
reset($array);
foreach($array as $key => $value) {
if ( $key == $last_key)
// Last key reached
}
To avoid the E_STRICT warning mentioned by #Warren Sergent
$array_keys = array_keys($array);
$last_key = end($array_keys);
$myarray = array(
'test1' => 'foo',
'test2' => 'bar',
'test3' => 'baz',
'test4' => 'waldo'
);
$myarray2 = array(
'foo',
'bar',
'baz',
'waldo'
);
// Get the last array_key
$last = array_pop(array_keys($myarray));
foreach($myarray as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
// Get the last array_key
$last = array_pop(array_keys($myarray2));
foreach($myarray2 as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
Since array_pop works on the temporary array created by array_keys it doesn't modify the original array at all.
$ php test.php
test1 -> foo
test2 -> bar
test3 -> baz
0 -> foo
1 -> bar
2 -> baz
Why not this very simple method:
$i = 0; //a counter to track which element we are at
foreach($array as $index => $value) {
$i++;
if( $i == sizeof($array) ){
//we are at the last element of the array
}
}
I know this is old, and using SPL iterator maybe just an overkill, but anyway, another solution here:
$ary = array(1, 2, 3, 4, 'last');
$ary = new ArrayIterator($ary);
$ary = new CachingIterator($ary);
foreach ($ary as $each) {
if (!$ary->hasNext()) { // we chain ArrayIterator and CachingIterator
// just to use this `hasNext()` method to see
// if this is the last element
echo $each;
}
}
My solution, also quite simple..
$array = [...];
$last = count($array) - 1;
foreach($array as $index => $value)
{
if($index == $last)
// this is last array
else
// this is not last array
}
If the items are numerically ordered, use the key() function to determine the index of the current item and compare it to the length. You'd have to use next() or prev() to cycle through items in a while loop instead of a for loop:
$length = sizeOf($arr);
while (key(current($arr)) != $length-1) {
$v = current($arr); doSomething($v); //do something if not the last item
next($myArray); //set pointer to next item
}
Simple approach using array_keys function to get the keys and get only first key [0] of reversed array which is the last key.
$array = array('a' => 1,'b' => 2,'c' => 3);
$last_key = array_keys(array_reverse($array, true))[0];
foreach($array as $key => $value) {
if ($last_key !== $key)
// THIS IS NOT THE LAST ELEMENT IN THE ARRAY doSomething();
}
NOTE: array_reverse reverse array take two arguments first array we want be reversed and second parameter true, to reverse the array and preserves the order of keys.
I have an array like this
array={'a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2'};
The array value might be different depending on the $_POST variables. My question is how to find the highest value in my array and return the index key. In my case, I need to get 'c' and 'd' and the value of 6. Not sure how to do this. Any helps would be appreciated. Thanks.
$max = max(array_values($array));
$keys = array_keys($array, $max);
Have a look at arsort which will sort an array in reverse order and maintain index association. So:
arsort($array);
This will end up with the largest values at the top of the array. Depending on what you need array_unique can remove duplicate values from your array.
$array = array(
'key1' => 22,
'key2' => 17,
'key3' => 19,
'key4' => 21,
'key5' => 24,
'key6' => 8,
);
function getHighest($array)
{
$highest = 0;
foreach($array as $index => $value)
{
if(is_numeric($value) && $value > $highest)
{
$highest = $index;
}
}
return $highest;
}
echo getHighest($array); //key5
Or this should do the magic, it would probably be faster than php built-in functions
$maxValue = -1;
$max = array();
foreach ($items as $key => $item) {
if ($item == $maxValue) {
$max[] = $key;
} elseif ($item > $maxValue) {
$max = array();
$max[] = $key;
$maxValue = $item;
}
}
How can I remove duplicate values from an array in PHP?
Use array_unique().
Example:
$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
Use array_values(array_unique($array));
array_unique: for unique array
array_values: for reindexing
//Find duplicates
$arr = array(
'unique',
'duplicate',
'distinct',
'justone',
'three3',
'duplicate',
'three3',
'three3',
'onlyone'
);
$unique = array_unique($arr);
$dupes = array_diff_key( $arr, $unique );
// array( 5=>'duplicate', 6=>'three3' 7=>'three3' )
// count duplicates
array_count_values($dupes); // array( 'duplicate'=>1, 'three3'=>2 )
$result = array();
foreach ($array as $key => $value){
if(!in_array($value, $result))
$result[$key]=$value;
}
The only thing which worked for me is:
$array = array_unique($array, SORT_REGULAR);
Edit : SORT_REGULAR keeps the same order of the original array.
sometimes array_unique() is not the way,
if you want get unique AND duplicated items...
$unique=array("","A1","","A2","","A1","");
$duplicated=array();
foreach($unique as $k=>$v) {
if( ($kt=array_search($v,$unique))!==false and $k!=$kt )
{ unset($unique[$kt]); $duplicated[]=$v; }
}
sort($unique); // optional
sort($duplicated); // optional
results on
array ( 0 => '', 1 => 'A1', 2 => 'A2', ) /* $unique */
array ( 0 => '', 1 => '', 2 => '', 3 => 'A1', ) /* $duplicated */
We can easily use arrar_unique($array); to remove duplicate elements
But the problem in this method is that the index of the elements are not in order, will cause problems if used somewhere else later.
Use
$arr = array_unique($arr);
$arr = array_values($arr);
print_r($arr);
Or
$arr = array_flip($arr);
$arr = array_flip($arr);
$arr = array_values($arr);
print_r($arr);
The first flip , flips the key value pair thus combines the elements with similar key(that was originally the value).
2nd flip to revert all the key value pairs. Finally array_value() sets each value with key starting from 0.
Note: Not to be used in associative array with predefined key value pairs
$a = array(1, 2, 3, 4);
$b = array(1, 6, 5, 2, 9);
$c = array_merge($a, $b);
$unique = array_keys(array_flip($c));
print_r($unique);
We can create such type of array to use this last value will be updated into column or key value and we will get unique value from the array...
$array = array (1,3,4,2,1,7,4,9,7,5,9);
$data=array();
foreach($array as $value ){
$data[$value]= $value;
}
array_keys($data);
OR
array_values($data);
explode(",", implode(",", array_unique(explode(",", $YOUR_ARRAY))));
This will take care of key associations and serialize the keys for the resulting new array :-)
Depending on the size of your array, I have found
$array = array_values( array_flip( array_flip( $array ) ) );
can be faster than array_unique.
There can be multiple ways to do these, which are as follows
//first method
$filter = array_map("unserialize", array_unique(array_map("serialize", $arr)));
//second method
$array = array_unique($arr, SORT_REGULAR);
If you concern in performance and have simple array, use:
array_keys(array_flip($array));
It's many times faster than array_unique.
This example is just an alternative.
<?php
$numbers = [1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,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,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1];
$unique_numbers = [];
foreach($numbers as $number)
{
if(!in_array($number,$unique_numbers)){
$unique_numbers[] = $number;
}
}
print(json_encode($unique_numbers)); //// Array is now 1,3,4,5,6,2,7, ....
That's a great way to do it. Might want to make sure its output is back an array again. Now you're only showing the last unique value.
Try this:
$arrDuplicate = array ("","",1,3,"",5);
foreach (array_unique($arrDuplicate) as $v){
if($v != "") { $arrRemoved[] = $v; }
}
print_r ($arrRemoved);
if (#!in_array($classified->category,$arr)){
$arr[] = $classified->category;
?>
<?php } endwhile; wp_reset_query(); ?>
first time check value in array and found same value ignore it
Remove duplicate values from an associative array in PHP.
$arrDup = Array ('0' => 'aaa-aaa' , 'SKU' => 'aaa-aaa' , '1' => '12/1/1' , 'date' => '12/1/1' , '2' => '1.15' , 'cost' => '1.15' );
foreach($arrDup as $k => $v){
if(!( isset ($hold[$v])))
$hold[$v]=1;
else
unset($arrDup[$k]);
}
Array ( [0] => aaa-aaa [1] => 12/1/1 [2] => 1.15 )
$arrDuplicate = array ("","",1,3,"",5);
foreach(array_unique($arrDuplicate) as $v){
if($v != "" ){$arrRemoved = $v; }}
print_r($arrRemoved);
try this short & sweet code -
$array = array (1,4,2,1,7,4,9,7,5,9);
$unique = array();
foreach($array as $v){
isset($k[$v]) || ($k[$v]=1) && $unique[] = $v;
}
var_dump($unique);
Output -
array(6) {
[0]=>
int(1)
[1]=>
int(4)
[2]=>
int(2)
[3]=>
int(7)
[4]=>
int(9)
[5]=>
int(5)
}
<?php
$arr1 = [1,1,2,3,4,5,6,3,1,3,5,3,20];
print_r(arr_unique($arr1));
function arr_unique($arr) {
sort($arr);
$curr = $arr[0];
$uni_arr[] = $arr[0];
for($i=0; $i<count($arr);$i++){
if($curr != $arr[$i]) {
$uni_arr[] = $arr[$i];
$curr = $arr[$i];
}
}
return $uni_arr;
}
Here I've created a second empty array and used for loop with the first array which is having duplicates. It will run as many time as the count of the first array. Then compared with the position of the array with the first array and matched that it has this item already or not by using in_array. If not then it'll add that item to second array with array_push.
$a = array(1,2,3,1,3,4,5);
$count = count($a);
$b = [];
for($i=0; $i<$count; $i++){
if(!in_array($a[$i], $b)){
array_push($b, $a[$i]);
}
}
print_r ($b);
It can be done through function I made three function duplicate returns the values which are duplicate in array.
Second function single return only those values which are single mean not repeated in array and third and full function return all values but not duplicated if any value is duplicated it convert it to single;
function duplicate($arr) {
$duplicate;
$count = array_count_values($arr);
foreach($arr as $key => $value) {
if ($count[$value] > 1) {
$duplicate[$value] = $value;
}
}
return $duplicate;
}
function single($arr) {
$single;
$count = array_count_values($arr);
foreach($arr as $key => $value) {
if ($count[$value] == 1) {
$single[$value] = $value;
}
}
return $single;
}
function full($arr, $arry) {
$full = $arr + $arry;
sort($full);
return $full;
}
As an alternative of array_unique() you may use php Set class
$array = array(1, 2, 2, 3);
$array = (new \Ds\Set($array))->toArray() ; // Array is now (1, 2, 3)
An alternative for array_unique() function..
Using Brute force algorithm
//[1] This our array with duplicated items
$matches = ["jorge","melvin","chelsy","melvin","jorge","smith"];
//[2] Container for the new array without any duplicated items
$arr = [];
//[3] get the length of the duplicated array and set it to the var len to be use for for loop
$len = count($matches);
//[4] If matches array key($i) current loop Iteration is not available in
//[4] the array $arr then push the current iteration key value of the matches[$i]
//[4] to the array arr.
for($i=0;$i
if(array_search($matches[$i], $arr) === false){
array_push($arr,$matches[$i]);
}
}
//print the array $arr.
print_r($arr);
//Result: Array
(
[0] => jorge
[1] => melvin
[2] => chelsy
[3] => smith
)
<?php
$a=array("1"=>"302","2"=>"302","3"=>"276","4"=>"301","5"=>"302");
print_r(array_values(array_unique($a)));
?>//`output -> Array ( [0] => 302 [1] => 276 [2] => 301 )`
I have done this without using any function.
$arr = array("1", "2", "3", "4", "5", "4", "2", "1");
$len = count($arr);
for ($i = 0; $i < $len; $i++) {
$temp = $arr[$i];
$j = $i;
for ($k = 0; $k < $len; $k++) {
if ($k != $j) {
if ($temp == $arr[$k]) {
echo $temp."<br>";
$arr[$k]=" ";
}
}
}
}
for ($i = 0; $i < $len; $i++) {
echo $arr[$i] . " <br><br>";
}
$array = array("a" => "moon", "star", "b" => "moon", "star", "sky");
// Deleting the duplicate items
$result = array_unique($array);
print_r($result);
ref : Demo