0

This is my two arrays:

$head_office = array(600,400,534,678,601,90);
$Sb_office = array(600,400,530,678,600,90,84);

My desire output:

array(600,400,678,90);

I am trying:

print_r(array_intersect($Sb_office,$head_office));

Output:

Array ( [0] => 600 [1] => 400 [3] => 678 [4] => 600 [5] => 90 )

How can I avoid the value 600 ?

NB: I am not removing duplicate values. I want to get matched values between 2 arrays.

Asif Iqbal
  • 1,132
  • 1
  • 10
  • 23
  • 9
    Assuming that you mean you want to avoid ___duplicating___ the value 600, then there's a magic little function called [array_unique()](http://www.php.net/manual/en/function.array-unique.php): `print_r(arry_unique(array_intersect($Sb_office,$head_office)));` – Mark Baker May 13 '16 at 13:35
  • yes it brings one value removing duplicate values. But I want to get matched value between my two arrays. Here, $head_office has only one 600. So after intersect result should have one 600. It is not removing duplicate values. – Asif Iqbal May 13 '16 at 13:40
  • Swap $Sb_office and $head_office in array_intersect. The order is important – ml_ May 13 '16 at 13:54

5 Answers5

0

Use array_unique().

$head_office = array(600,400,534,678,601,90);
$Sb_office = array(600,400,530,678,600,90,84);

print_r(array_unique(array_intersect($Sb_office,$head_office)));

Output

Array ( [0] => 600 [1] => 400 [3] => 678 [5] => 90 ) 
RJParikh
  • 4,096
  • 1
  • 19
  • 36
  • yes it brings one value removing duplicate values. But I want to get matched value between my two arrays. Here, $head_office has only one 600. So after intersect result should have one 600. It is not removing duplicate values – Asif Iqbal May 13 '16 at 13:41
  • 1
    @AdamSmith Why does this not work for you? It seems to work fine. – CodeGodie May 13 '16 at 14:01
  • 1
    yes I am trying to explain it that its working with both array_unique() ans assoc() what is the diffrence in oputput? thanks. @CodeGodie – RJParikh May 13 '16 at 14:04
0

Use array_unique

Additionally you can use array_values to alter the keys of new array.

$head_office = array(600,400,534,678,601,90);
$Sb_office = array(600,400,530,678,600,90,84);

print_r(array_values(array_unique(array_intersect($Sb_office,$head_office))));

OUTPUT

Array ( [0] => 600 [1] => 400 [2] => 678 [3] => 90 )

Suyog
  • 2,472
  • 1
  • 14
  • 27
0

It seams that you want to avoid duplicate value 600. you can do it using array_unique() like below

print_r(arry_unique(array_intersect($Sb_office,$head_office)));
Vijayanand Premnath
  • 3,415
  • 4
  • 25
  • 42
0

Swap $head_office and $Sb_office

<?php
$head_office = array(600,400,534,678,601,90);
$Sb_office   = array(600,400,530,678,600,90,84);

print_r( array_intersect($head_office, $Sb_office) );

Output:

Array
(
    [0] => 600
    [1] => 400
    [3] => 678
    [5] => 90
)
ml_
  • 392
  • 2
  • 9
-1

I have gotten a partial answer:

print_r( array_intersect_assoc($head_office, $Sb_office) );
Asif Iqbal
  • 1,132
  • 1
  • 10
  • 23