Can you use array_unique exceeding a value of the array?

1

There is a possibility that array_unique take the elements you want from an array, for example, we have an array with keys and names, and we want to eliminate duplicate names by ignoring keys that may be different.

I know there is no point in doing this but I could not think of another example

That is, if we have an array with this data

1000 Mortadelo Garcia
1001 Filemon Fernandez
1002 Eduardo ManosTijeras
1003 Filemon Fernandez

If we would use array_unique with this data we would return the same array since the id changes, but if the id would be ignored, this array would remain

1000 Mortadelo Garcia
1001 Filemon Fernandez
1002 Eduardo ManosTijeras

I'm even interested in the possibility that this can be done:

1000 Mortadelo Garcia
1001,1003 Filemon Fernandez
1002 Eduardo ManosTijeras

Maybe array_unique does not have these possibilities and simply compares all the data in the array. So the next question comes up, how could you make these comparisons.

    
asked by Lombarda Arda 17.05.2017 в 12:37
source

2 answers

1

No, array_unique() does not support the functionality you want, but you can easily implement it:

<pre><?php
$datos = [
    1000 => 'Mortadelo Garcia',
    1001 => 'Filemon Fernandez',
    1002 => 'Eduardo ManosTijeras',
    1003 => 'Filemon Fernandez',
];

function array_unicos($array) {
    $resultado = [];
    foreach(array_unique($array) as $elemento) {
        $claves = array_keys($array, $elemento);
        $resultado[implode(',', $claves)] = $elemento;
    }
    return $resultado;
}

var_export(array_unique($datos));
?></pre>
<pre><?php
var_export(array_unicos($datos));
?></pre>

The result would be:

array (
  1000 => 'Mortadelo Garcia',
  1001 => 'Filemon Fernandez',
  1002 => 'Eduardo ManosTijeras',
)
array (
  1000 => 'Mortadelo Garcia',
  '1001,1003' => 'Filemon Fernandez',
  1002 => 'Eduardo ManosTijeras',
)

Keep in mind that when finding several matches, the index must be converted to text in order to contain the original indexes separated by commas.

    
answered by 17.05.2017 / 14:11
source
0
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

This method what it does is show the number of times a value is found is an array, for example in the case that I have set it would come out:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

It's not exactly what you ask, but I do not think there's any way in php capable of doing that, attached doc with all the methods for arrays.

    
answered by 17.05.2017 в 13:15