Create a name for a variable with php

Asked

Viewed 42 times

1

Well I’m with a question where php itself has to create the variable name, I’ve used this feature several times. The problem I am now trying to use this 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 on it, however it is returning me this error:

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

Does anyone know what it can be?

  • is this a multi-dimensional array? I believe what’s wrong is $$table[] = array..., it should be $$table = array...

  • I actually use the [] to link the data. I edited the question.

  • Do you want to $tabela be an array is that? and at position 1 what value do you want it to have?

  • I don’t want to create a variable with the name tabela1 and then place an array on it.

  • Why not just use $tabela1 https://ideone.com/VIQsRv ?

  • So I have a for where I have to create some arrays, and it is easier for the code itself to create the names.

Show 1 more comment

2 answers

5


The problem was occurring in the $$table[1], at this point PHP tries to define the index of an array that doesn’t exist yet, you need to put around the variable chaves for PHP to understand that first it needs to create the variable and then set its index. The correct one would be as follows:

<?php

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

$valor = "Qualquer coisa";

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

?>
  • It worked here, thank you very much.

1

First you create the array then 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
); 
  • 1

    That way it didn’t work in my code, but @Bruno Rigolon’s form worked.

  • I tested here with PHP 7 and it worked well, but the answer from @Bruno Rigolon is more correct to do. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.