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.

1
  • The question is not clear. Please, make it easier to understand! Commented Jun 16, 2021 at 5:36

2 Answers 2

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"
]
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.