Check and return duplicates array php - php

I would like to check if my array has any duplicates and return the duplicated values in an array.
I want this to be as efficient as possible.
Example:
$array = array( 1, 2, 2, 4, 5 );
function return_dup($array); // should return 2
$array2 = array( 1, 2, 1, 2, 5 );
function return_dup($array2); // should return an array with 1,2
Also the initial array is always 5 positions long

this will be ~100 times faster than array_diff
$dups = array();
foreach(array_count_values($arr) as $val => $c)
if($c > 1) $dups[] = $val;

You can get the difference of the original array and a copy without duplicates using array_unique and array_diff_assoc:
array_diff_assoc($arr, array_unique($arr))

function array_dup($ar){
return array_unique(array_diff_assoc($ar,array_unique($ar)));
}
Should do the trick.

You can do like this:
function showDups($array)
{
$array_temp = array();
foreach($array as $val)
{
if (!in_array($val, $array_temp))
{
$array_temp[] = $val;
}
else
{
echo 'duplicate = ' . $val . '<br />';
}
}
}
$array = array(1,2,2,4,5);
showDups($array);
Output:
duplicate = 2

function returndup($array)
{
$results = array();
$duplicates = array();
foreach ($array as $item) {
if (in_array($item, $results)) {
$duplicates[] = $item;
}
$results[] = $item;
}
return $duplicates;
}

in addition to gumbo's answer:
function returndup($arr)
{
return array_diff_key($arr, array_unique($arr));
}

I did some tests and indeed #user187291's variant is the fastest. But, it turns out that #Gumbo's and #faebser's alternative are almost as fast, #faebser's being just slightly faster than #Gumbo's and sometimes even fastest of all.
Here's the code I used
$array = array(1, "hello", 1, "world", "hello");
$times = 1000000;
$start = microtime(true);
for ($i = 0; $i < $times; $i++) {
$dups = array();
foreach(array_count_values($array) as $val => $c)
if( $c > 1) $dups[] = $val;
}
$end = microtime(true);
echo 'variant 1 (user187291): ' . ($end - $start);
echo '<br><br><br>';
$start = microtime(true);
for ($i = 0; $i < $times; $i++)
$dups = array_unique(array_diff_assoc($array, array_unique($array)));
$end = microtime(true);
echo 'variant 2 (JAL): ' . ($end - $start);
echo '<br><br><br>';
$start = microtime(true);
for ($i = 0; $i < $times; $i++)
$dups = array_diff_assoc($array, array_unique($array));
$end = microtime(true);
echo 'variant 3 (Gumbo): ' . ($end - $start);
echo '<br><br><br>';
$start = microtime(true);
for ($i = 0; $i < $times; $i++)
$dups = array_diff_key($array, array_unique($array));
$end = microtime(true);
echo 'variant 4 (faebser): ' . ($end - $start);
echo '<br><br><br>';

I have found another way to return duplicates in an array
function printRepeating($arr, $size)
{
$i;
$j;
for($i = 0; $i < $size; $i++)
for($j = $i + 1; $j < $size; $j++)
if($arr[$i] == $arr[$j])
echo $arr[$i], " ";
}
printRepeating($array, sizeof($array,0);

If you need a solution that will work with an array of arrays (or any array values other than integers or strings) try this:
function return_dup( $arr ) {
$dups = array();
$temp = $arr;
foreach ( $arr as $key => $item ) {
unset( $temp[$key] );
if ( in_array( $item, $temp ) ) {
$dups[] = $item;
}
}
return $dups;
}
$arr = array(
array(
0 => 'A',
1 => 'B',
),
array(
0 => 'A',
1 => 'B',
),
array(
0 => 'C',
1 => 'D',
),
array(
0 => 'C',
1 => 'D',
),
array(
0 => 'E',
1 => 'F',
),
array(
0 => 'F',
1 => 'E',
),
array(
0 => 'Y',
1 => 'Z',
),
);
var_export( return_dup( $arr ) );
/*
array (
0 => array (
0 => 'A',
1 => 'B',
),
1 => array (
0 => 'C',
1 => 'D',
),
)
*/

As per your problem if you have duplicate values then you have to return those values. I write a function for this problem. If your array has duplicate values this function returns these values within the array otherwise it returns null values. Here is an example:
function containsDuplicate($array_values) {
$duplicates_values = [];
for($i = 0; $i < count($array_values); $i++){
for ($j=$i+1; $j <count($array_values) ; $j++) {
if ($array_values[$i] == $array_values[$j]) {
$duplicates_values[] = $array_values[$i];
}
}
}
if(count($duplicates_values) > 0){
return $duplicates_values;
}
}

$duplicate_array = array();
for($i=0;$i<count($array);$i++){
for($j=0;$j<count($array);$j++){
if($i != $j && $array[$i] == $array[$j]){
if(!in_array($array[$j], $duplicate_array)){
$duplicate_array[] = $array[$j];
}
}
}
}

Related

Insertion sort php

Have someone an idea why the programm doesn't enter in the function?
This is a simple insertion sort algorithm.
<?php
function insert($my_array)
{
for($i=0;$i<count($my_array);$i++){
$val = $my_array[$i];
$j = $i-1;
while($j>=0 && $my_array[$j] > $val){
$my_array[$j+1] = $my_array[$j];
$j--;
}
$my_array[$j+1] = $val;
}
return $my_array;
$test_array = array(3, 0, 2, 5, -1, 4, 1);
echo "Original Array :\n";
echo implode(', ',$test_array );
echo "\nSorted Array :\n";
print_r(insert($test_array));
?>
} is missing try now
function insert($my_array)
{
for($i=0;$i<count($my_array);$i++){
$val = $my_array[$i];
$j = $i-1;
while($j>=0 && $my_array[$j] > $val){
$my_array[$j+1] = $my_array[$j];
$j--;
}
$my_array[$j+1] = $val;
}
return $my_array;
}
$test_array = array(3, 0, 2, 5, -1, 4, 1);
echo "Original Array :\n";
echo implode(', ',$test_array );
echo "\nSorted Array :\n";
print_r(insert($test_array));
OutPut : Original Array : 3, 0, 2, 5, -1, 4, 1 Sorted Array : Array ( [0] => -1 [1] => 0 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )
$data_set = [3,44,38,5,15,26,27,2,46,4];
function insertion_sort($data_set){
$number_of_items = count($data_set);
for($i = 0; $i <= $number_of_items - 2; $i++){
$k = $i;
for($j = $i + 1; $j > 0; $j--){
if($data_set[$j] < $data_set[$k]){
$temp = $data_set[$j];
$data_set[$j] = $data_set[$k];
$data_set[$k] = $temp;
}
if($k > 0 )
$k--;
}
}
return $data_set;
}
echo '<pre>';
print_r(insertion_sort($data_set));
echo '</pre>';

Numeric multidimensional array php

I have this numeric multidimensional array in php. It's Playfair matrix and I want to get the keys of a letter from the matrix.
Let's say I have the letter "P", which is on the third row(0 to 4) and second column(0 to 4). I have tried several things array_keys(not working as I want it to), functions to get the key of the first level of the array, making the array one dimensional and doing some magic tricks...Nothing works and I would like some help.
This is the function that gets the keys of the first level:
function array_search2($needle, $haystack){
$l = count($haystack);
for ($i=0; $i < $l; $i++) {
if (in_array($needle, $haystack[$i])) return $i;
}
return false;
}
I want to have this array with letters, to get two letters from it, to get these two letters their coordinates(from the PLayfair matrix) and to comprate their rows/columns.
Thank you and I'll post any code that is needed.
Edit : I'm posting all I have:
$keyword = str_replace(' ','', $_POST['keyword']);
$plaintext = str_replace(' ','', $_POST['plaintext']);
$key = str_split($keyword); //string to array
$plain = str_split($plaintext); //string to array
$alphabet = array(
0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f',
6 => 'g', 7=> 'h', 8 => 'i', 9 => 'j', 10 => 'k', 11 => 'l',
12 => 'm', 13 => 'n', 14 => 'o', 15 => 'p', 16 => 'q', 17 => 'r',
18 => 's', 19 => 't', 20 => 'u', 21 => 'v', 22 => 'w', 23 => 'x',
24 => 'y');
for ($i=0; $i < count($key); $i++) {
for ($j=0; $j < count($alphabet) ; $j++) {
if ($keyword[$i] == $alphabet[$j]) {
unset($alphabet[$j]);
}
}
}
$keywordFilpped = array_flip($key);
$alphabetFlipped = array_flip($alphabet);
$mergedFlipped = $keywordFilpped + $alphabetFlipped;
$i = 0;
foreach ($mergedFlipped as $key => $value) {
$mergedFlipped[$key] = $i;
$i++;
}
$merged = array_flip($mergedFlipped);
$index = 0;
for ($i=0; $i < 5; $i++) {
for ($j=0; $j < 5; $j++) {
$matrix[$i][$j] = $merged[$index];
$index++;
}
}
echo "PLAYFAIR MATRIX:<br>";
for ($i=0; $i < 5; $i++) {
for ($j=0; $j < 5; $j++) {
echo $matrix[$i][$j];
}
echo "<br>";
}
if you have a matrix should check with 2 for like following code:
for($i = 1; $i <= 11; $i++)
{
for($j = 1; $j <= 11; $j++)
{
if($array[$i][$j] == 'p') echo "row=$i and col = $j";
}
}
in the above example i check all rows and rows cols
use from this function
function array_search2($needle, $haystack){
$i = 0;
foreach($haystack as $key => $value)
{
$j = 0;
foreach($value as $key2 => $value2)
{
if($value2 == $needle)
return array($i, $j);
$j++;
}
$i++;
}
return false;
}
this function will return an array contain row and col of found status or false;
i tested with following data:
$array = array( 0 => array(0 => 'a', 1=> 'b'), 1 => array(0 => 'c', 1=> 'd'));
print_r(array_search2('d', $array));
// out put Array ( [0] => 1 [1] => 1 )
I've improved your function, which will return keys if match found, irrespective of depth, See example below:
function getArrayKeys($needle, $haystack, $depth = 0) {
$keys = array();
foreach($haystack as $key => $value) {
if(is_array($value)){
$result = getArrayKeys($needle, $value, $depth + 1);
if(!empty($result) || $result === 0) {
if (is_array($result)) {
$keys = array_merge($keys, $result);
} else {
$keys[] = $result;
}
$keys[] = $key;
}
if(!empty($keys) && $depth > 0)
return $keys;
} elseif($value == $needle) {
return $key;
}
}
return !empty($keys) ? array_reverse($keys) : false;
}
$arr = array(
array('A', 'B', 'C'),
array('D', 'F', 'E'),
array('Z', 'Y', 'X'),
array('f' => '44', 'g' => array('99'))
);
$keys = getArrayKeys('99', $arr);
Output:
Array
(
[0] => 3
[1] => g
[2] => 0
)
See it running: https://eval.in/571698

How can sort an array without using sort() function in php?

I'm trying to sort an array without using sort() function of php. I have tried so far and also google but unable to find result.
What I Need exactly
$arr = array(80, 90, 100, 10, 50, 3);
I want to sort this array in ascending. i can do it using sort() function but I want to do without using sort() function.
Are you looking for this:
<?php
$arr = array(80, 90, 100, 10, 50, 3);
for($a = 0; $a < count($arr); $a++) {
for($b = 0; $b < count($arr)-1; $b ++){
if($arr[$b] > $arr[$b+1]) {
$temp = $arr[$b+1];
$arr[$b+1]=$arr[$b];
$arr[$b]=$temp;
}
}
}
print_r($arr);
?>
Implementing QuickSort in PHP
or
Quicksort recursive.php
function quicksort( $array ) {
if( count( $array ) < 2 ) {
return $array;
}
$left = $right = array( );
reset( $array );
$pivot_key = key( $array );
$pivot = array_shift( $array );
foreach( $array as $k => $v ) {
if( $v < $pivot )
$left[$k] = $v;
else
$right[$k] = $v;
}
return array_merge(quicksort($left), array($pivot_key => $pivot), quicksort($right));
}
Usage :
$arr = array(80, 90, 100, 10, 50, 3);
$arr = quicksort($arr);
print_r($arr);
use this
$srtArray=array(80, 90, 100, 10, 50, 3);
for ($i=0; $i<count($srtArray); $i++) {
for ($j=0; $j<count($srtArray); $j++) {
// Compare two elements of array
if ($srtArray[$j] > $srtArray[$i]){
$tmp = $srtArray[$i];
$srtArray[$i] = $srtArray[$j];
$srtArray[$j] = $tmp;
}
}
}
//Print an array after sorting
for($i=0;$i<count($srtArray);$i++){
echo $srtArray[$i]."<br>\n";
}
You should use QuickSort because is practically the fastest way to sort an array of data. PHP's array sorting function sort() uses QuickSort. QuickSort is O(n log n).
<?php
$arr = array(80, 90, 100, 10, 50, 3);
function quicksort( $array ) {
if( count( $array ) < 2 ) {
return $array;
}
$left = $right = array( );
reset( $array );
$pivot_key = key( $array );
$pivot = array_shift( $array );
foreach( $array as $k => $v ) {
if( $v < $pivot )
$left[$k] = $v;
else
$right[$k] = $v;
}
return array_merge(quicksort($left), array($pivot_key => $pivot), quicksort($right));
}
$array = quicksort( $arr );
print_r($array);
Output:
Array
(
[0] => 3
[1] => 10
[2] => 50
[3] => 80
[4] => 90
[5] => 100
)
But if you can't use any built in function you can use this implementation of BubbleSort:
$arr = array(80, 90, 100, 10, 50, 3);
function bubbleSort ($items) {
$size = count($items);
for ($i=0; $i<$size; $i++) {
for ($j=0; $j<$size-1-$i; $j++) {
if ($items[$j+1] < $items[$j]) {
arraySwap($items, $j, $j+1);
}
}
}
return $items;
}
function arraySwap (&$arr, $index1, $index2) {
list($arr[$index1], $arr[$index2]) = array($arr[$index2], $arr[$index1]);
}
$array = bubbleSort( $arr );
print_r($array);
Reference:
http://pageconfig.com/post/implementing-quicksort-in-php
http://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Quicksort#PHP
http://www.codecodex.com/wiki/Bubble_sort#PHP
Hope this will be the more optimized. Try this:
$arr = array(80, 90, 100, 10, 50, 3);
$count = count($arr);
for ($i = 0; $i < $count - 1; $i++ ) {
for ($j = $i+1; $j < $count; $j++ ) {
if ($arr[$i] > $arr[$j]) {
$temp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $temp;
}
}
}
print_r($arr);
$arr = array(80, 90, 100, 10, 50, 3,34,1,890);
for($i = 0; $i < count($arr); $i++) {
for($x = 0; $x < count($arr)-1; $x ++){
if($arr[$x] > $arr[$x+1]) {
$temp = $arr[$x+1];
$arr[$x+1]=$arr[$x];
$arr[$x]=$temp;
}
}
}
print_r($arr);

How to change a multidimension array element with a function

I have an array like this:
<?php
$arr = [
'a' => [
'a1' => [
'A11', 'A12', 'A13'
]
]
];
I can change the A13 element in an easy way:
$arr['a']['a1'][2] = 'A13 NEW';
But I want to do this with a function, something like this:
f($arr, ['a', 'a1', 2], 'A13 New');
I write this function using eval and I don't like it.
<?php
function f(&$array, $index, $value) {
$e = '$array';
for ($i = 0, $l = count($index); $i < $l; $i++) {
$e .= '[$index[' . $i . ']]';
}
$e .= ' = $value;';
// now we have `$e` like this
// $array[$index[0]][$index[1]][$index[2]] = $value;
eval($e);
}
How can I write this function without using eval?
$arr = array(
'a' => array(
'a1' => array(
'A11', 'A12', 'A13'
)
)
);
function f(&$arr, $index, $value) {
$tmp = &$arr;
foreach ($index as $key) {
$tmp = &$tmp[$key];
}
$tmp = $value;
}
f($arr, array('a', 'a1', 2), 'A13 New');
//$arr['a']['a1'][2] = 'A13 NEW';
var_dump($arr);

How to get the uneven keys from an array?

I have to create a function that copy the array(that i pass to the function) with only uneven keys. Example:
$a = array(
'0' => '0',
'one => 'one',
'1' => '1',
'two' => 'two'
)
I have to get:
$result = array(
'one => 'one',
'two' => 'two'
)
I have created the follow function, it works, but maybe I need to optimize it(maybe exists a function that does this job). Advice?
private clean($values){
$vv = array();
$keys = array_keys($values);
for($i=1; $i < count($values); $i+=2) $vv[$keys[$i]] = $values[$keys[$i]];
return $vv;
}
Thanks
$even = range(0, count($array), 2);
source
UPDATE:
for ($i = 0, $c = count($array); $i <= $c; $i = $i + 2) {
$even = array_push($even, $array[$i]);
}
Try
$outputArray = array();
$keyToAdd = false;
foreach( $inputArray as $key => $value ) {
if( $keyToAdd ) {
$outputArray[$key] = $value;
}
$keyToAdd = !$keyToAdd;
}

Categories