Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advancing index keys in an array

I have an array with numerical incrementing keys starting at 0, like 0 1 2 3 4 5 ....etc. I need to assign new keys to the array in the following manner

  • The first three keys keep their index number

  • Every 4th key gets incremented by 4

  • The two keys after the fourth gets incremented by 1again

I know I need to use a foreach loop ( seems the simplest way anyway ) to build a new array with newly assigned keys. My problem is the calculation of the keys

HERE IS WHAT I HAVE SEEN IN RELATION

Here is my current array keys

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

and this is what I need them to be

0 1 2 6 7 8 12 13 14 18 19 20 24 25 26 30

Lets break this down into 3 key groups with the old array key on the top and the new array key at the bottom

1st group

0 1 2

0 1 2

2nd group

3 4 5

6 7 8

3rd group

6 7 8

12 13 14

4th group

9 10 11

18 19 20

etc etc......

When you look at the relationship between the two array keys, you'll see the following:

  • The old array keys 0, 1 and 2 keep their key value

  • The old array keys 3, 6, 9 etc, if multiplied by 2, gives you the new array key value

  • The old array keys 4, 7, 10 etc, if multiplied by 2 and you subtract 1 from that total, you get the new array key for that specific key

  • The old array keys 5, 8, 11 etc, if multiplied by 2 and you subtract 2 from the total, you get the new array key for that specific key

Alternatively, if you subtract the old key from the new key, you get the following answer

  • 0 for the 1st group

  • 3 for the 2nd group

  • 6 for the 3rd group

  • 9 for the 4th group

  • etc etc.....

POSSIBLE SOLUTION

The only solution I can think of is to use the modulus operator (inside my foreach loop), check the current key against the modulus result and then calculate my new key

Example:

if ( $key%3 == 0 && $key != 0 ) {
    $new_key = $key * 2;
} elseif ( ( $key - 1 ) %3 == 0 && $key != 1 ) {
    $new_key = ( $key * 2 ) - 1;
} elseif ( ( $key - 2 ) %3 == 0 && $key != 2 ) {
    $new_key = ( $key * 2 ) - 2;
} else {
    $new_key = $key;
}

$new_array[$new_key] = $value;

MY QUESTION

Isn't there a smarter more mathematical way of doing this?

like image 462
Pieter Goosen Avatar asked Mar 16 '23 19:03

Pieter Goosen


1 Answers

Try the following:

$new_key = floor($old_key / 3) * 3 + $old_key
like image 63
Luke Avatar answered Mar 18 '23 10:03

Luke