Dynamic php function from list of values

Hi! I have a list of values, in my case color codes. Those will be used to create buttons on the frontend to let the user (logged in) change the color. My php function works very well and updates a user field with the value of the color.

Now I would like to make the function dynamic so I can add colors (based on a structure field for example) and don’t need to write a function for every color - that’s where I struggle - I am not sure how to use variables in the function or shall I put it in a controller or can I have the function just in the foreach loop? Many thanks!

array + html:

$colors = array('4747EB', '009e76', 'FF3333');
$i = 0;

foreach($colors as $color){
    $i++;
    ?>
    <a href="?color<?= $i ?>=true" style="background:#<?= $color ?>;">
        <?= $color ?>
    </a>
<?php };

single php function

function color1() {

    $kirby = kirby();
    $kirby->impersonate();        
    $kirby->user()->update([
        'color' => $color,
    ]);

    go('/some-page');

};

if (isset($_GET['color1'])) {
    color1();
};       

This is done by passing a parameter to a function

function color(string $color)
{
      $kirby = kirby();
    $kirby->impersonate();        
    $kirby->user()->update([
        'color' => $color,
    ]);

    go('/some-page');
}

Your link:

 <a href="?color=<?= $color ?>" style="background:#<?= $color ?>;">
        <?= $color ?>
    </a>

No need for the counter.

Then call the function with parameter:

if (isset($color = $_GET['color'])) {
    color($color);
}

I get this exception:

Whoops \ Exception \ ErrorException (E_COMPILE_ERROR)
Cannot use isset() on the result of an expression (you can use "null !== expression" instead)

Also does the function need to be in a controller or just before the foreach loop?
And the function call within the foreach loop?

if ($color = get('color'))

Yeah! Thanks you so much @texnixe you’re always very helpful and super fast :pray:t2: