Variable variable in php

4

I need to generate a variable with an arbitrary name. I have the following code, which does not work:

$vv = mysql_query("SELECT * FROM $tabela ORDER BY rand() LIMIT 3");
$i=1;
while($v = mysql_fetch_array($vv)){
  $vertical.$i=$v['arquivo'];
  $i++;
}

echo'
<img src="img/fotos/'.$vertical1.'"> <br>
<img src="img/fotos/'.$vertical2.'"> <br>
<img src="img/fotos/'.$vertical3.'">
';

I would like the query to return 3 variables: $vertical1 , $vertical2 and $vertical3

Note: In the database the 'file' field has the 'format' included. Ex .: foto.jpg

Obs2: I believe the problem is in concatenation $vertical.$i ...

    
asked by anonymous 13.12.2016 / 01:02

3 answers

8

With variable variables would look like this:

$varname = 'vertical' . $i;
$$varname = $v['arquivo'];

I find this somewhat ugly and confusing, I'd rather use an array:

<?php
$vv = mysql_query("SELECT * FROM $tabela ORDER BY rand() LIMIT 3");
$vertical = array();

while($v = mysql_fetch_array($vv)) {
    $vertical[] = $v['arquivo'];
}

echo '
    <img src="img/fotos/'.$vertical[0].'"> <br>
    <img src="img/fotos/'.$vertical[1].'"> <br>
    <img src="img/fotos/'.$vertical[2].'">
';

PS: You need to update all your mysql_* calls to mysqli_* , since your code is incompatible with newer versions of PHP .

    
13.12.2016 / 02:08
3

I agree with @bfavaretto ... The code with $variavel$i would be a bit confusing. To increment using his response, I put a loop in the images, because if you change the LIMIT of SQL, then you do not need to add the <img> tag again, so it already does it alone:

<?php
$vv = mysql_query("SELECT * FROM $tabela ORDER BY rand() LIMIT 3");
$vertical = array();

while($v = mysql_fetch_array($vv)) {
    $vertical[] = $v['arquivo'];
}

for($i = 0; $i < count($vertical); $i++){
   echo '<img src="img/fotos/'.$vertical[$i].'"><br />';
}
    
13.12.2016 / 02:26
2

Responding more of the same, I could just delimit with braces.

Example:

$str1 = 'a';
$str2 = 'b';
${$str1.$str2} = 'c';

echo $ab;

Something more specific to the question code:

$i = '1';
${'vertical'.$i} = 'foo';

echo $vertical1;

I agree with the comments on the code because what you are doing makes readability difficult. There are certain cases where it can be well applied, but it does not appear to be the case that presented in the question. However, I can not judge whether what you do is right or wrong because I am oblivious to your business logic.

    
13.12.2016 / 03:37