Question

I found an example here that shows an example like this:

<?php 
for ($i = 1; $i <= 5; $i++) {
  ${a.$i} = "value";
}    

echo "$a1, $a2, $a3, $a4, $a5";
//Output is value, value, value, value, value
?>

Is it possible to modify it to work like this:

for($x=1; $x<11; $x++)
{
    ${title.$x} = $row['${title.$x}'];
    ${brief.$x} = $row['${brief.$x}'];
    ${cost.$x} = $row['${cost.$x}'];

    echo "<tr>
               <td>${title.$x}</td>
          </tr>
          <tr>
               <td>${brief.$x}</td>
          </tr>
         ";
 }

The $row array comes from a mysql query.

Was it helpful?

Solution

for($x=1; $x<11; $x++)
{
    ${'title'.$x} = $row['title'.$x]; // will be like: $title1 = $row['title1']; (if you mean that)
    ${'brief'.$x} = $row['brief'.$x];
    ${'cost'.$x} = $row['cost'.$x];

    echo "<tr>
               <td>${'title'.$x}</td>
          </tr>
          <tr>
               <td>${'brief'.$x}</td>
          </tr>
         ";
 }

If your variable name is same with the key name in the $row, you could use extract($row) to get all variables you want.

But in your case, I think using the $row array directly is not bad idea.

OTHER TIPS

As long as you are ok with converting everything in $row to a variable, the simplest way is to use PHP's extract() (converts an array into variables), by just writing extract($row);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top