0

Ok I am pretty sure there is a simple solution, and I am missing something on this but

lets say I have this a simple array:

Array
(
    [0] => 79990
    [1] => 79040
    [2] => 79100
    [3] => 79990
    [4] => 79490
    [5] => 79290
    [6] => 79990
)

0, 3 and 6 are the same value

how do I mark/highlight these values on a foreach loop? result should be something like:

Array
(
    [0] => *79990*
    [1] => 79040
    [2] => 79100
    [3] => *79990*
    [4] => 79490
    [5] => 79290
    [6] => *79990*
)

edit: typos

Shanti
  • 15
  • 5
  • Check the linked duplicate to see how to find array values that occur more than once. Then check if the `$number_of_occurrences > 1` and apply the styling based on that. – Amal Murali Mar 24 '14 at 19:04
  • Joel, it is not a duplicate, that questions asks to detect how many duplicates a value has. – Shanti Mar 24 '14 at 19:13
  • Related technique that does not perform multiple cycles over the input array: [Update column value in each row where the row is identical to another row in the same 2d array](https://stackoverflow.com/q/75094492/2943403) – mickmackusa Jan 17 '23 at 06:45

2 Answers2

4

This should do the trick:

<?php

    $array = array( '79900',
                    '79040',
                    '79100',
                    '79990',
                    '79490',
                    '79290',
                    '79990');

    $count = array_count_values($array);

    echo "<pre>".print_r($array, true)."</pre>";

    foreach($array as $val)
    {
        if($count[$val]>1) {
            $output[] = "*".$val."*";
        } else {
            $output[] = $val;
        }
    }

    echo "<pre>".print_r($output, true)."</pre>";

?>

Outputs:

Array
(
    [0] => 79900
    [1] => 79040
    [2] => 79100
    [3] => 79990
    [4] => 79490
    [5] => 79290
    [6] => 79990
)

Array
(
    [0] => 79900
    [1] => 79040
    [2] => 79100
    [3] => *79990*
    [4] => 79490
    [5] => 79290
    [6] => *79990*
)

Note: Your [0] isn't actually the same as [3] and [6], but I'm assuming this is just a typo

Let me know how you get on!

0
$array = array("79900","79040","79100","79990","79490","79290","79990");
$count = array_count_values( $array );
$list  = array();
foreach( $count as $index => $value ){
    if( $value > 1 ){
        $list[] = "*" . $index . "*";
    }else{
        $list[] = $index;
    }
}

Note that the repeated index is removed

Joel Jaime
  • 459
  • 2
  • 9