Home > database >  Without built-in functions how to find differences in two arrays
Without built-in functions how to find differences in two arrays

Time:05-25

I have to find the difference for both array, i have tried but i am not getting my expected.can you please help here.

<?php

    $firstArray = array(3,4,5,6);
    $secondArray = array(4, 5);
    
    $outputArray = array();
    foreach($firstArray as $firstArrayItem) {
        foreach($secondArray as $secondArrayItem) {
            if($firstArrayItem != $secondArrayItem) {
                $outputArray[] = $firstArrayItem;
            }
        }
        
    }
    print_r($outputArray);

Expected output

[3,6]

Note: we should not use PHP inbuild functions.

CodePudding user response:

a) Use a boolean value to check it:

<?php

$firstArray = array(3,4,5,6);
$secondArray = array(4, 5);

$outputArray = array();

foreach($firstArray as $firstArrayItem) {
$found = false;
    foreach($secondArray as $secondArrayItem) {
        if($firstArrayItem == $secondArrayItem) {
            $found = true;
        }
    }
    
    if($found == false){
        $outputArray[] = $firstArrayItem;
    }
    
}
print_r($outputArray);

Output: https://3v4l.org/8CuS8

b) Another way using for() loop: https://3v4l.org/9JZrW

CodePudding user response:

$firstArray = array(3,4,5,6);
$secondArray = array(4, 5, 7);

$outputArray = diffArray($firstArray, $secondArray);
$outputArray = diffArray($secondArray, $firstArray, $outputArray);

function diffArray($arr1, $arr2, $result = array()) {
    foreach($arr1 as $arr11) {
        $isExist = false;
        foreach($arr2 as $arr22) {
            if($arr11 === $arr22) {
                $isExist = true;
            }
        }
        if(!$isExist) $result[] = $arr11;
        
    }
    return $result;
}
print_r($outputArray);

CodePudding user response:

Here is a solution that does not give a different result when the input arrays as swapped.

So it will give the same result for this:

$firstArray = array(3, 4, 5, 6);
$secondArray = array(4, 5);

as for this:

$firstArray = array(4, 5);
$secondArray = array(3, 4, 5, 6);

Also, it will deal with duplicate values as follows:

$firstArray = array(4, 4, 4);
$secondArray = array(3, 4, 6);

for which I would expect the output to be:

array(3, 4, 4, 6)  // Only one 4 is common and should be excluded.

The code for having this behaviour could be (without inbuilt functions except for print_r):

$assoc = [];
foreach($firstArray as $value) {
    $assoc[$value][] = 1;
}
foreach($secondArray as $value) {
    $assoc[$value][] = -1;
}
foreach($assoc as $value => $list) {
    $count = 0;
    foreach($list as $delta) $count  = $delta;
    for($i = $count > 0 ? $count : -$count; $i > 0; $i--) {
        $result[] = $value;
    }
}
print_r($result);
  •  Tags:  
  • php
  • Related