0

I have two arrays as displayed below and I want to be able to select ONLY values in Array 1 and exist in Array 2

This is my first array:

<pre>array(4) {
  [0]=>
  array(1) {
    ["user_id"]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    ["user_id"]=>
    string(1) "2"
  }
  [2]=>
  array(1) {
    ["user_id"]=>
    string(1) "3"
  }
  [3]=>
  array(1) {
    ["user_id"]=>
    string(1) "4"
  }
}

This is my second array:

<pre>array(5) {
  [0]=>
  array(1) {
    ["user_id"]=>
    string(1) "5"
  }
  [1]=>
  array(1) {
    ["user_id"]=>
    string(1) "1"
  }
  [2]=>
  array(1) {
    ["user_id"]=>
    string(1) "4"
  }
  [3]=>
  array(1) {
    ["user_id"]=>
    string(1) "4"
  }
  [4]=>
  array(1) {
    ["user_id"]=>
    string(1) "5"
  }
}

I hope to find a more elegant way of doing this.

Oyedele Femi
  • 157
  • 4
  • 14

1 Answers1

2

Oyedele, so there is this PHP Function called array_interesect which will only return values present in the arguments.

Click for more info

<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>

And that returns the following:

Array
(
    [a] => green
    [0] => red
)

UPDATE: For your case you would need to use array_uintersect

Here is the code

// Creating your Arrays

$array1 = array(
           array('user_id' => '1'),
           array('user_id' => '2'),
           array('user_id' => '3'),
           array('user_id' => '4'),
        );

$array2 = array(
           array('user_id' => '5'),
           array('user_id' => '1'),
           array('user_id' => '4'),
           array('user_id' => '4'),
           array('user_id' => '5'),
        );

// Preforming comparison

$intersect = array_uintersect($array1, $array2, 'compareDeepValue');
print_r($intersect);

// Custom Comparison Function

function compareDeepValue($val1, $val2)
{
   return strcmp($val1['user_id'], $val2['user_id']);
}

And here is the output:

Array
(
    [0] => Array
        (
            [user_id] => 1
        )

    [3] => Array
        (
            [user_id] => 4
        )

Click here for live demo.

Riz-waan
  • 603
  • 3
  • 13
  • @OyedeleFemi No Problem, if it helped you please upvote the answer and mark the checkmark. :) Here is a related question by the way: https://stackoverflow.com/questions/5653241/using-array-intersect-on-a-multi-dimensional-array – Riz-waan Jun 24 '20 at 18:30