-1

I have a list of values eg. 1 - 100, what I need to do is the following: There are values relating to these number, so 1 = pink, 2 = blue, 3 = grey, etc. when it gets to 12 = green, it has to start over, so then 13 would be pink again, and the whole sequence is restarted.

Any assistance will be greatly appreciated. All coding done in PHP.

5
  • Show us your code please..!! Commented Nov 28, 2017 at 10:59
  • 1
    Stack Overflow is not a free code writing service. You are expected to try to write the code yourself. After doing more research if you have a problem you can post what you've tried with a clear explanation of what isn't working and providing a Minimal, Complete, and Verifiable example. I suggest reading How to Ask a good question. Commented Nov 28, 2017 at 10:59
  • and what have you tried so far? Commented Nov 28, 2017 at 10:59
  • use the modulo operator (%). Commented Nov 28, 2017 at 11:00
  • You're looking for modulo operator - php.net/manual/en/language.operators.arithmetic.php Commented Nov 28, 2017 at 11:01

2 Answers 2

2

Just use the modulo and a array of colors.

<?php

$number = 13;
$colors = ['pink',   'blue',   'grey',
           'yellow', 'red',    'green',
           'white',  'black',  'purple',
           'brown',  'orange', 'ocean'];

// number-1 if you want the pink color
echo $colors[($number-1) % count($colors)];
Sign up to request clarification or add additional context in comments.

3 Comments

Clean and elegant solution. I would replace 12 with count($colors)
@tkovs: it's cleaner than my switch if we need just one action. +1
@cbaconnier yeah, count($colors) is more readable, ty.
0

Simple task for modulo operator and switch.

<?php

$number = 98;

switch ($number % 12) {
    case 1:
        $color: pink;
        break;

    case 2:
        $color: blue;
        break;

    ...
}

echo $color;

?>

1 Comment

Thank you! Exactly what I was looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.