Create a name for a variable with php

1

Well I'm having an issue where php itself has to create the variable name, I've used this feature several times. The problem I am now trying to use is in an array, as follows:

// Cria o nome da variável
$tabela = "tabela1";

// Cria o array
$$tabela[1] = array(
    "valor" => $valor
); 

Well, the code had to create a variable with the name $tabela1 and put the array in it, but it is returning this error:

Notice: Uninitialized string offset: 3 in teste.php on line 3

Does anyone know what it can be?

    
asked by anonymous 14.06.2017 / 14:54

2 answers

5

The problem was occurring in the $$ table [1], at this point, PHP tries to set the index of an array that does not exist yet, you need to put around the chaves variable for PHP to understand what first it needs create the variable and then set its index. The correct one would look like this:

<?php

// Cria o nome da variável
$tabela = "tabela1";

$valor = "Qualquer coisa";

// Cria o array
${$tabela}[1] = array(
    "valor" => $valor
); 

?>
    
14.06.2017 / 15:11
1

First you create the array after you assign the values.

// Cria o nome da variável
$tabela = "tabela1";

// Cria o array
$$tabela = array();

// Atribui os valores
$$tabela[1] = array(
    "valor" => $valor
); 
    
14.06.2017 / 15:10