0

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

3 Answers 3

1

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

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

Comments

1

use intVal to remove the A char and keep number:

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

Comments

0

You should not use the associative arrays for this purpose!

However the simplest method is to convert your string '6A' into a number with intval(string) PHP function.

intval("6A") returns 6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.