'Return Results of a Function Within a Variable to Change the Varible

I am trying to pass a function into an existing variable to set specific locations within my template. However when I use the function switch I am not receiving any results.

function posicionnavbar($posicion) {
    switch ($posicion) {
        case 'top':
            return 'top';
        case 'soc':
            return 'soc';
        case 'nav':
            return 'nav';
        case 'usr':
            return 'usr';
    }
}

And the variable I am attempting to append to.

$omni[posicionnavbar($tabs['position'])] .= $nuevo_tab;

More Info:

$tabs['position']

Is either - top, soc, nav, or usr

$omni***

Is the variable used within my template for each location. IE: $omnitop

I have passed the variable using $omni .= $nuevo_tab; and using $omni within my template to confirm everything was working, with success. Which lead me to something being off with my function.

How can I pass my function into my variable to change the variable name?

end results would output one of the following:

$omnitop .= $nuevo_tab;
$omnisoc .= $nuevo_tab;
$omninav .= $nuevo_tab;
$omniusr .= $nuevo_tab;


Solution 1:[1]

You can also create an array $omni with keys returned from your function. Then it will be easier to iterate over the results

 <?php
        

function posicionnavbar($posicion) {
    switch ($posicion) {
        case 'top':
            return 'top';
        case 'soc':
            return 'soc';
        case 'nav':
            return 'nav';
        case 'usr':
            return 'usr';
    }
}

$tabs['position'] = 'top';
$nuevo_tab = "Something";

$omni[posicionnavbar($tabs['position'])] .= $nuevo_tab;

//let's imagine you got the value of $nuevo_tab here (for simulate the loop)
$omni['soc'] .= "Something related with soc";
$omni['nav'] .= "Something related with nav";    
$omni['usr'] .= "Something related with usr";   

foreach ($omni as $key => $value) {
    echo "\n";
    echo "the key {$key} has the value -> {$value}";
}

Anyway, your answer is valid. The one I have proposed is only for convenience. In case in the future you want to access what seem to be variables that are related, with a simple loop

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1