Skip to content
Advertisement

Showing duplicate keys in associative array in PHP

I have an array of numbers:

[Note: $arrNum is dynamic. It’s created using rand(). So every time the values will be different. It’s not fixed values.]

$arrNum = [2, 5, 6, 6, 8];

Now there’ll will be an associative array named $arrNumDouble. The key of $arrNumDouble is the value of $arrNum and the value corresponding to the key is the double of the key.

$arrNumDouble = [];

for ($i=0; $i < sizeof($arrNum); $i++) {

    if (array_key_exists($arrNum[$i], $arrNumDouble)) {

        //repeated values in the $arrNum array, the 
        //key in the $arrNumDouble array is 
         //supplemented with a letter, e.g. “A”

        $arrNumDouble[$arrNum[$i]."A"] = $arrNum[$i] * 2;
    } else {
        $arrNumDouble[$arrNum[$i]] = $arrNum[$i] * 2;
    }    
};

Now $arrNumDouble becomes:

$arrNumDouble = array
                (
                  [2] => 4,
                  [5] => 10,
                  [6] => 12,
                  [6A] => 12,
                  [8] => 16
                 )

From this $arrNumDouble I can easily display on screen like this:

<?php foreach($arrNumDouble as $key => $value): ?>
       <tr>
           <td><?php echo $key; ?></td>
           <td><?php echo $value; ?></td>
       </tr>
  <?php endforeach; ?>

Num    Double
2        4
5        10
6        12
6A       12
8        16

But how can I display like this:

Num    Double
2        4
5        10
6        12
6        12   //without letter A
8        16

Advertisement

Answer

You can store results as array of arrays as approach:

<?php
$arrNum = [2, 5, 6, 6, 8];

$arrNumDouble = array_map(
    function($el) {
        return [$el, 2*$el];
    },
    $arrNum
);

#var_export($arrNumDouble);

foreach($arrNumDouble as $el) {
    echo "2 * $el[0] = $el[1]" . PHP_EOL;
}

share PHP code

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement