how to count the array values? [duplicate] - php

How can I count the number of element inside an array with value equals a constant?
example,
$myArray = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
how can I directly know how many "Ben" is inside?

$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];

You can do this with array_keys and count.
$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));
Output:
3

To count a value in a two dimensional array, here is the useful snippet to process and get count of a particular value-
<?php
$list = [
['id' => 1, 'userId' => 5],
['id' => 2, 'userId' => 5],
['id' => 3, 'userId' => 6],
];
$userId = 5;
echo array_count_values(array_column($list, 'userId'))[$userId]; // outputs: 2

Use the array_count_values function.
$countValues = array_count_values($myArray);
echo $countValues["Ben"];

Use array_count_values() function . Check this link http://php.net/manual/en/function.array-count-values.php

define( 'SEARCH_STRING', 'Ben' );
$myArray = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$count = count(array_filter($myArray,function($value){return SEARCH_STRING === $value;}));
echo $count, "\n";
Output:
3

try the array_count_values() function
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
http://php.net/manual/en/function.array-count-values.php

Try the PHP function array_count_values.

If you want to count ALL the same occurences inside the array, here's a function to count them all, and return the results as a multi-dimensional array:
function countSame($array) {
$count = count($array);
$storeArray = array();
while ($count > 0) {
$count--;
if ($array[$count]) {
$a = $array[$count];
$counts = array_count_values($array);
$counts = $counts[$a];
$tempArray = array($a, $counts);
array_push($storeArray, $tempArray);
$keys = array_keys($array, $a);
foreach ($keys as $k) {
unset($array[$k]);
} //end of foreach ($keys as $k)
} //end of if ($array[$count])
} //end of while ($count > 0)
return $storeArray;
} //end of function countSame($array)

array_count_values only works for integers and strings. If you happen to want counts for float/numeric values (and you are heedless of small variations in precision or representation), this works:
function arrayCountValues($arr) {
$vals = [];
foreach ($arr as $val) { array_push($vals,strval($val)); }
$cnts = array_count_values($vals);
arsort($cnts);
return $cnts;
}
Note that I return $cnts with the keys as strings. It would be easy to reconvert them, but I'm trying to determine the mode for the values, so I only need to re-convert the first (several) values.
I tested a version which looped, creating an array of counts rather than using array_count_values, and this turned out to be more efficient (by maybe 8-10%)!

Related

Fetch row, explode and delete duplicates - PHP [duplicate]

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,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,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;
}
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

PHP array_unique is not returning unique values [duplicate]

My array is :
$array= array(4,3,4,3,1,2,1);
And I'd like to output it like below:
Output = 2
(As 2 is present only once)
This is what I've tried:
$array = array(4, 3, 4, 3, 1, 2, 1);
$array1 = array(4, 3, 4, 3, 1, 2, 1);
$array_diff = array_diff($array, $array1);
*Read last section of this an for the most stable technique the avoids fringe case issues -- it is also the most verbose.
One-liner with no loops: (Demo)
var_export(array_keys(array_intersect(array_count_values($array),[1])));
The breakdown:
array_keys( // return the remaining keys from array_count_values
array_intersect( // filter the first array by second
array_count_values($array), // count number of occurrences of each value
[1] // identify the number of occurrences to keep
)
)
if you (or any future reader) wants to keep more values, replace the second parameter/array in array_intersect().
for instance:
you want to keep 1,2,and 3: array(1,2,3) or [1,2,3]
p.s. For the record, you can use array_filter() with a custom function to omit all non-1 count values, but I have used array_intersect() because the syntax is more brief and IMO easier to read.
p.s. thought I'd revisit and include a PHP7.4 technique and compare against other function-based techniques...
Code: (Demo)
$numbers = [4, 3, 4, 3, 1, 2, 1];
var_export(
array_keys(
array_intersect(
array_count_values($numbers),
[1]
)
)
);
echo "\n---\n";
var_export(
array_keys(
array_filter(
array_count_values($numbers),
function($count) {
return $count === 1;
}
)
)
);
echo "\n---\n";
// PHP7.4+
var_export(
array_keys(
array_filter(
array_count_values($numbers),
fn($count) => $count === 1
)
)
);
*For similar tasks which have values which are not guaranteed to be integers, array_count_values() will complain with "Warning: array_count_values(): Can only count string and integer values".
Even a classic loop that uses values as first level keys like #LF00's answer will suffer potential side effects due to floats and numeric values being cast as integers automatically.
This means that a more general-use solution would be: (Demo)
$result = [];
foreach ($array as $index => $value) {
foreach ($array as $i => $v) {
if ($value === $v && $index !== $i) {
continue 2; // duplicate found, stop checking this value; do not retain
}
}
$result[] = $value;
}
var_export($result);
You could use the array_count_values() php function.
For example:
$numbers = [4, 3, 4, 3, 1, 2, 1];
// build count array as key = number and value = count
$counter_numbers = array_count_values($numbers);
print_r($counter_numbers);
Output :
Array
(
[4] => 2
[3] => 2
[1] => 2
[2] => 1
)
Then loop through the new array to get non-repeated values :
$unique_numbers = [];
foreach ($counter_numbers as $number => $count) {
if ($count === 1) {
$unique_numbers[] = $number;
}
}
print_r($unique_numbers);
Output :
Array
(
[0] => 2
)
You can do it like this: Count the occurrences of each element, then filter out the occurrences bigger than 1.
$array = [4, 3, 4, 3, 1, 2, 1];
foreach ($array as $v)
{
$arr[$v][] = 1; // doesn't matter if 1 is set to a different value
}
foreach($arr as $k => $v)
{
if (count($v) == 1) {
$o[] = $k;
}
}
print_r($o);
result:
Array
(
[0] => 2
)
If in your scenario there will be only one unique value you could use:
$array= array(4,3,4,3,1,2,1);
$singleValue = array_search(1, array_count_values($array));
var_dump($singleValue) // Outputs: 2

PHP - count specific array values

How can I count the number of element inside an array with value equals a constant?
example,
$myArray = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
how can I directly know how many "Ben" is inside?
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
You can do this with array_keys and count.
$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));
Output:
3
To count a value in a two dimensional array, here is the useful snippet to process and get count of a particular value-
<?php
$list = [
['id' => 1, 'userId' => 5],
['id' => 2, 'userId' => 5],
['id' => 3, 'userId' => 6],
];
$userId = 5;
echo array_count_values(array_column($list, 'userId'))[$userId]; // outputs: 2
Use the array_count_values function.
$countValues = array_count_values($myArray);
echo $countValues["Ben"];
Use array_count_values() function . Check this link http://php.net/manual/en/function.array-count-values.php
define( 'SEARCH_STRING', 'Ben' );
$myArray = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$count = count(array_filter($myArray,function($value){return SEARCH_STRING === $value;}));
echo $count, "\n";
Output:
3
try the array_count_values() function
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
http://php.net/manual/en/function.array-count-values.php
Try the PHP function array_count_values.
If you want to count ALL the same occurences inside the array, here's a function to count them all, and return the results as a multi-dimensional array:
function countSame($array) {
$count = count($array);
$storeArray = array();
while ($count > 0) {
$count--;
if ($array[$count]) {
$a = $array[$count];
$counts = array_count_values($array);
$counts = $counts[$a];
$tempArray = array($a, $counts);
array_push($storeArray, $tempArray);
$keys = array_keys($array, $a);
foreach ($keys as $k) {
unset($array[$k]);
} //end of foreach ($keys as $k)
} //end of if ($array[$count])
} //end of while ($count > 0)
return $storeArray;
} //end of function countSame($array)
array_count_values only works for integers and strings. If you happen to want counts for float/numeric values (and you are heedless of small variations in precision or representation), this works:
function arrayCountValues($arr) {
$vals = [];
foreach ($arr as $val) { array_push($vals,strval($val)); }
$cnts = array_count_values($vals);
arsort($cnts);
return $cnts;
}
Note that I return $cnts with the keys as strings. It would be easy to reconvert them, but I'm trying to determine the mode for the values, so I only need to re-convert the first (several) values.
I tested a version which looped, creating an array of counts rather than using array_count_values, and this turned out to be more efficient (by maybe 8-10%)!

Search an array and create an array from the results

I have an associated array in php of subjects with either 1 or 0 as the second value.
e.g: ([maths] => 1, [science] => 0, [english] => 1)
How can i create a new array of items that have a value of 1? i.e. (maths, english)
Thanks
$output = array_filter($input, function($v) {
return $v == 1;
});
This should do the trick (but requires PHP 5.3) - see array_filter().
$results = array();
foreach($array as $k=>$v){
if($v == 1){
$results[] = $k;
}
}
If you can guarantee that values will only ever be 1 or 0, then you can do an array_diff() to pick up every value that isn't 0.
$array = array( 'maths' => 1,
'science' => 0,
'english' => 1);
$newArray = array_diff($array, array(0));
var_dump($newArray);
EDIT
or the corresponding array_intersect() method to match every value that is a 1:
$newArray2 = array_intersect($array, array(1));
var_dump($newArray2);
If you want the original keys to become the values in your new array, then just wrap the expression in an array_keys() function. e.g.
$newArray2 = array_keys(array_intersect($array, array(1)));
$array2 = array()
foreach ( $array as $key=>$val ){
if($val == 1)
{
$array2[] = $key;
}
}

How to remove duplicate values from an array in PHP

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,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,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

Categories