Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build a variable name in PHP out of two variables

Depending on the current page, I would like to change the css of the chosen menu module and make others different, etc. All that while building dynamically the page before loading.

My problem is that I have a serie of variables going by this structure :

$css_(NAME_OF_MODULE)

To know what variable must be set , I have another variable I received in parameters of this functions, called

$chosen_menu

Say $chosen_Menu = "C1", I would like to add content to $css_C1. Thus, what I want is to create a variable name out of 2 variables, named $css_C1

I have tried :

${$css_.$chosen_menu} = "value";

But it doesnt seem to work. Any clue ?

like image 382
Alexandre Bolduc Avatar asked Nov 13 '11 15:11

Alexandre Bolduc


3 Answers

That probably won't just work. PHP supports full indirection though, so something like this will work.

$varName = $css."_".$chosen_menu;
$$varName = "value";

If not, it will probably be attempting to interpret $css_ as a variable name in your second code sample, so just change that to $css."_".$chosen_menu.

like image 59
slugonamission Avatar answered Sep 21 '22 09:09

slugonamission


Check out http://php.net/manual/en/language.variables.php

You should be able to use:

$menu = $css . '_' .$chosen_menu;
$$menu = 'some value';

or

${$menu} = 'some value';
like image 43
Jim H. Avatar answered Sep 20 '22 09:09

Jim H.


$nr = 1;        
       ${'name' . $nr} = 20 ;        
       var_dump($name1);   
like image 39
Dragos Custura Avatar answered Sep 17 '22 09:09

Dragos Custura