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

3
  • 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. Commented Mar 24, 2014 at 19:04
  • Joel, it is not a duplicate, that questions asks to detect how many duplicates a value has. Commented Mar 24, 2014 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 Commented Jan 17, 2023 at 6:45

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! this works as expected! and yeah, it was a typo, then a copy paste typo :P
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

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.