FlatulentBadger Posted February 25, 2018 Share Posted February 25, 2018 Hi there, I'm new here and fairly new to PHP, so be gentle please. I have a 2D array such as: Array ( [0] => Array ( [0] => 28 [1] => 6 ) [1] => Array ( [0] => 6 ) [2] => Array ( [0] => 61 [1] => 6 [2] => 28 ) ) From which I need to end up with an array containing only the elements that exist in all the 2nd dimensions. In this case it would be just 6. I could iterate over everything starting with the smallest array " [0] => Array ( [0] => 6 )", but it seems a bit clumsy, and I was wondering if I have missed any PHP array function that may make this easier, or if anyone has any better suggestions? Cheers, Bob. Link to comment Share on other sites More sharing options...
benanamen Posted February 25, 2018 Share Posted February 25, 2018 You mean like this? $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); foreach ($cars[1] as $v) { echo "$v<br>"; } ?> Link to comment Share on other sites More sharing options...
Barand Posted February 25, 2018 Share Posted February 25, 2018 Use array_intersect to check for common values $data = [ [28, 6], [6], [61,6,28] ]; $result = []; foreach ($data as $arr) { $result = empty($result) ? $arr : array_intersect($result, $arr); } // view result echo '<pre>', print_r($result, 1), '</pre>'; Link to comment Share on other sites More sharing options...
FlatulentBadger Posted February 25, 2018 Author Share Posted February 25, 2018 You mean like this? $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); foreach ($cars[1] as $v) { echo "$v<br>"; } ?> I don't, I appreciate my question may not be entirely clear though, too much mixing of languages, and beer. Barand, got the jist. Link to comment Share on other sites More sharing options...
FlatulentBadger Posted February 25, 2018 Author Share Posted February 25, 2018 Use array_intersect to check for common values $data = [ [28, 6], [6], [61,6,28] ]; $result = []; foreach ($data as $arr) { $result = empty($result) ? $arr : array_intersect($result, $arr); } // view result echo '<pre>', print_r($result, 1), '</pre>'; Thanks Barand, this is exactly what I was after, I am off for a bit of a deeper dive into the array_intersect docs now. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.