Search code examples
phparrayscycle

How to repeatedly assign values to numbers in PHP?


I need to assign three colors to multiple years and the colors repeat.

The currently working code is an array with the year numbers as keys and colors as values.

There are only three colors (black, blue, green) but an (hopefully ;)) unlimited amount of years.

Example Code:

$year=2017;
$color=array(
  2017 => "black",
  2018 => "blue",
  2019 => "green",
  2020 => "black",
  2021 => "blue",
  2023 => "green",
  2024 => "black"
  );
echo "$color[$year]

As you can see, the colors repeat every three years and I'd like to avoid writing the array until "forever" to make it more maintainable. Does anyone have an idea how to implement that (maybe in a function)?


Solution

  • You can use modulus operator:

    function colourFromYear($year){
    
        $colours = ['green','black','blue'];
        return $colours[$year % 3];
    }
    
    echo colourFromYear(2017); //black
    echo colourFromYear(2018); //blue
    echo colourFromYear(2019); //green
    echo colourFromYear(7327); //black