How to concatenate a variable in the middle of another variable?

1

I would like to make the contents of one variable form another variable, for example:

$name = 'clientes';
$default_$name_list = "Lista de clientes";

I want to make the default variable be $default_clientes_list , is there any way to do this in PHP?

    
asked by anonymous 01.06.2018 / 19:57

3 answers

4

You can get something like this using variable variables in PHP .

$name = 'clientes';
$lista_var = "default_{$name}_list";
$$lista_var = "Lista de clientes";

echo $default_clientes_list;

See working .

Or even simplifying some more without assigning to the intermediate variable.

$name = 'clientes';
${"default_{$name}_list"} = "Lista de clientes";

echo $default_clientes_list;

In my opinion, I do not recommend following this line. This greatly impairs the readability of the code without having an apparent benefit. It just makes it more complex and difficult for anyone reading the code.

    
01.06.2018 / 20:06
3

Look, I do not know if you can do this, but you can do it in array.

For example:

$name="clientes";
$defaultList['clientes']= "Lista de clientes";
$defaultList['representantes'] = "Lista de representantes";

And then you pull what you want:

echo $defaultList[$name]; // Lista de clientes;
    
01.06.2018 / 20:05
1

Your example does not work because PHP is looking for the $name_list variable, which does not exist.

To get the effect you want, I think it would be this way.

$varName = sprintf("default_%s_list", $name /* ou 'clientes' */);
$$varName = /* você terá uma variável $default_clientes_list com o valor que passar aqui */;

However, I do not recommend this practice either. In this case and in several other similarities I believe that the use of Arrays is better.

    
01.06.2018 / 20:11