0

I have a mixed array type something like:

Array
(
    [0] => 368
    [1] => Array
        (
            [0] => 384
            [1] => 383
        )

)

I was trying to get the unique count as count(array_unique($arr_val)) but its throwing error: Array to string conversion

I want to count that nested as one type. For example, if another same array [384,383] appear on another index that should not be added on the total count as that won't be the unique one. In this case the unique count should be greater than 1.

Aayush Dahal
  • 856
  • 1
  • 17
  • 51

2 Answers2

0

Primitive algorithm to count unique top level array elements:

  1. hash array top level elements
  2. build temp unique hashes array
  3. count temp array

For example:

$arr = [368, [0 => 384, 1 => 383],[0 => 384, 1 => 383]];

$hashedUniqueArr = [];
foreach ($arr as $val) {
    $hash =  md5(serialize($val));
    if (!in_array($hash, $hashedUniqueArr)) {
        $hashedUniqueArr[] = $hash;
    }
}
echo 'unique top level elements: ' . count($hashedUniqueArr);
Mindau
  • 690
  • 6
  • 19
0

Use SORT_REGULAR as the second parameter.

$array = ['test', 'test', [10,20,30], [10, 20, 30], [20, 30], 'test_one', 'test_two'];

print_r(array_unique($array, SORT_REGULAR));

Result:

array:5 [
  0 => "test"
  2 => array:3 [
    0 => 10
    1 => 20
    2 => 30
  ]
  4 => array:2 [
    0 => 20
    1 => 30
  ]
  5 => "test_one"
  6 => "test_two"
]
Biswajit Biswas
  • 859
  • 9
  • 20