how to interpret a string as a php variable

0

I intend to do this:

echo $.'variable';

as a result of this:

//Solicitamos a la BD todas las id de la tabla categorias
$data = $this->Global_model->get_select_array('idcategoria', 'categoria_tmp', TRUE);            

//rastreamos todo el contenido de data para que de ella surja otra consulta
foreach ($data as $key) 
{
    //Creamos la variable where para definir la busqueda en la BD
    $where = array('id_categoria' => $key['idcategoria']);
    //Consultamos a la BD para conseguir todas las preguntas
    $Preguntas[$key['idcategoria']] = $this->Global_model->get_where('pregunta_tmp', $where, TRUE);             
}

//Extraemos las variables otorgadas por $key['idcategoria']
extract($Preguntas);

Now try this:

parse_str($variable); //Pero admite un solo formato

All this with the purpose of interpreting a string as a variable:

<tbody>
      <?php foreach ($.'variable' as $key => $value): ?>

      <?php endforeach ?>
</tbody>

Then the question is: How can I interpret a string as a variable in php?

    
asked by Alexandro Arce 09.11.2017 в 21:50
source

2 answers

2

Let's see if the following are useful:

$str = 'Hola mundo';
$variable = 'str';

echo ${ $variable };

In the echo I am passing a string to compose the name of the variable, this is passing it between the keys. I have previously defined the variable, so that it does not have an undefined error. I do not know if it's what you're looking for. If you want to compose the variables dynamically, the same, between the keys:

$arr = array();
for ( $i= 0; $i < 10; $i++ ) {

    ${ 'var' . $i } = $i;
    $arr[ $i ] = ${ 'var' . $i };
}
print_r( $arr );
    
answered by 09.11.2017 в 22:22
1

You can use Variable variables where you can access a variable using a string:

<?php
$q = "hola mundo";
echo ${'q'};// hola mundo

?>

So in your case it would be:

 <?php foreach (${'variable'} as $key => $value): ?>

  <?php endforeach ?>

Although the documentation gives an advertenecia:

  

The additional differentiation of a variable property that is a   matrix has a different semantics between PHP 5 and PHP 7. The guide   PHP 7.0 migration includes more details on the types of   expressions that have changed and how to place keys to avoid   ambiguities.

So it is up to you whether to use it or not.

    
answered by 09.11.2017 в 22:08