3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

intersect of array-containing arrays

Last updated at Posted at 2018-04-20

#objective
to propagate how great built-in functions are

baseline

$arr1 = ["a", "b"];
$arr2 = ["a", "c"];
var_export(array_intersect($arr1, $arr2));
//array (
//  0 => 'a',
//)

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
-- array_intersect/note

so what if the parameters were arrays of array(and so on)?

$arr3 = [["a"], ["b"]];
$arr4 = [["a"], ["c"]];
var_export(array_intersect($arr1, $arr2));
// this causes "PHP Notice:  Array to string conversion"
// and echoes
// array (
//   0 => 
//   array (
//     0 => 'a',
//   ),
//   1 => 
//   array (
//     0 => 'b',
//   ),
// )
// because (string)["a"] or (string)["b"] or (string)["c"] should be "Array"

solution

use array_uintersect;

var_export(array_uintersect($arr3, $arr4, function($a, $b) { if ($a == $b) return 0; else return -1;}));
//array (
//  0 => 'a',
//)

and read document.

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?