Alexandre Bolduc
Alexandre Bolduc

Reputation: 825

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 ?

Upvotes: 6

Views: 6751

Answers (4)

slugonamission
slugonamission

Reputation: 9642

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.

Upvotes: 5

Dragos Custura
Dragos Custura

Reputation: 131

$nr = 1;        
       ${'name' . $nr} = 20 ;        
       var_dump($name1);   

Upvotes: 4

Niko
Niko

Reputation: 26730

I'm not sure if I get you right, but how about this:

${$css."_".$chosen_menu} = "value";

Upvotes: 0

Jim H.
Jim H.

Reputation: 5579

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';

Upvotes: 2

Related Questions