note 114233 added to function.array-intersect

From: Date: Mon, 27 Jan 2014 17:30:18 +0000
Subject: note 114233 added to function.array-intersect
Groups: php.notes 
Request: Send a blank email to php-notes+get-198364@lists.php.net to get a copy of this message
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"] ---- Server IP: 72.52.91.14 Probable Submitter: 72.52.91.14 ---- Manual Page -- http://php.net/manual/en/function.array-intersect.php Edit -- https://master.php.net/note/edit/114233 Del: integrated -- https://master.php.net/note/delete/114233/integrated Del: useless -- https://master.php.net/note/delete/114233/useless Del: bad code -- https://master.php.net/note/delete/114233/bad+code Del: spam -- https://master.php.net/note/delete/114233/spam Del: non-english -- https://master.php.net/note/delete/114233/non-english Del: in docs -- https://master.php.net/note/delete/114233/in+docs Del: other reasons-- https://master.php.net/note/delete/114233 Reject -- https://master.php.net/note/reject/114233 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#198364) next »