-2

I have two arrays, for example $session and $post with 100+ values. I will compare the $post array values with $session array. If post is different then it will be taken to result array else not.

We can try this using array_diff_assoc($post, $session) and foreach(). Which one is faster?

Phil
  • 157,677
  • 23
  • 242
  • 245
Octopus
  • 165
  • 2
  • 14
  • What of your question [here](https://stackoverflow.com/questions/50458982/comparing-two-arrays-to-find-difference-using-php-function)? – hungrykoala May 22 '18 at 06:03
  • 7
    Why don't you try it and see which is faster ~ [Simplest way to profile a PHP script](https://stackoverflow.com/q/21133/283366) – Phil May 22 '18 at 06:04
  • @Phil I have tried it. PHP_functions looks slower than foreach() – Octopus May 22 '18 at 06:09

2 Answers2

1

For profiling, Phil has suggested a great way in his reply, but I will link it here too, just in case: Simplest way to profile a PHP script

Practically, you need to know what each approach does. in array_diff_assoc, you are returning the difference between 2 collections, after comparing the key/value couples for each element. It will then return an array that contains the entries from array1 that are not present in array2 or array3, etc.

In a for each loop, you will need to hard code the same function (assuming that's what you need). You will need to take the first element, then look for the combination in your other arrays. If it matches your requirements, you will save it into your output array, or even print it directly.

Same principles apply, but then again, it will be up to profiling to determine the faster approach. Try doing so on a large number of big arrays, as the difference isn't noticeable at smaller scales.

Rabih Melko
  • 68
  • 10
0

I'll leave this as a stub/example, please edit, or use for profiling.

<?php

$before = [
    'name' => 'Bertie',
    'age' => '23'
];
$after  = [
    'name' => 'Harold',
    'age' => '23',
    'occupation' => 'Bus driver' 
];

function changed_1($after, $before) {
    return array_diff_assoc($after, $before);
}

function changed_2($after, $before) {
    $changed = [];
    foreach($after as $k => $v) {
        if(isset($before[$k]) && $before[$k] !== $v)
            $changed[$k] = $v;
        if(!isset($before[$k]))
            $changed[$k] = $v;
    }

    return $changed;
}

var_export(changed_1($after, $before));
var_export(changed_2($after, $before));

Output:

array (
  'name' => 'Harold',
  'occupation' => 'Bus driver',
)array (
  'name' => 'Harold',
  'occupation' => 'Bus driver',
)
Progrock
  • 7,373
  • 1
  • 19
  • 25
  • I've put some code here https://3v4l.org/pS8uc with over 4000 entries all different values (worst case). Ignore the results on their evaluater and run yourself or profile differently. For me the array_diff_assoc is faster. – Progrock May 22 '18 at 07:49