note 114233 deleted from function.array-intersect by cmb

From: Date: Sun, 09 Feb 2020 08:30:37 +0000
Subject: note 114233 deleted from function.array-intersect by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-214069@lists.php.net to get a copy of this message
Note Submitter: tim at zeroedin dot com ---- Note... this function does not seem intuitive for doing intersection of flat arrays, in the sense that an intersection are common values between. This is an issue if you are doing a for loop over the results of an intersect function, as shown below, wherein the for loop iterates over something different depending on order. Below is example of a function whioch I think works correctly, the output from original function, and new function. function array_value_mutual_intersection($array1, $array2) { $hashMap = array(); $output = array(); foreach($array1 as $item) $hashMap[$item] = ''; foreach($array2 as $item) if(isset($hashMap[$item])) array_push($output, $item); return $output; } $a = ['one', 'two', 'three', 'four']; $b = ['three', 'two']; echo "Original array a = " . json_encode($a) . "\n"; echo "Original array b = " . json_encode($b) . "\n"; echo "PHP array_intersect says interesection of (a,b) is: " . json_encode(array_intersect($a,$b)) . "\n"; echo "PHP array_intersect says interesection of (b,a) is: " . json_encode(array_intersect($b,$a)) . "\n\n"; echo "My intersect function says intersection of (a,b) is: " . json_encode(array_value_mutual_intersection($a, $b)) . "\n"; echo "My intersect function says intersection of (b,a) is: " . json_encode(array_value_mutual_intersection($b, $a)) . "\n\n"; -------output------ $ php test.php Original array a = ["one","two","three","four"] Original array b = ["three","two"] PHP array_intersect says interesection of (a,b) is: {"1":"two","2":"three"} PHP array_intersect says interesection of (b,a) is: ["three","two"] My intersect function says intersection of (a,b) is: ["three","two"] My intersect function says intersection of (b,a) is: ["two","three"]

« previous php.notes (#214069) next »