2

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.

4
  • 1
    Seriously, does every row contain 10 titles, 10 briefs and 10 costs fields??? Commented May 23, 2012 at 2:13
  • Move the quotes when referencing your $row - $row[${'title'.$x}]; Commented May 23, 2012 at 2:17
  • 1
    You badly need to look at your database design. Why are title1 title2 ... not separate rows? Commented May 23, 2012 at 2:18
  • YES! my rows have ten data fields! it is normalized though. One date has up to ten parts and a title for each part. Commented May 23, 2012 at 3:40

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

3 Comments

the code speaks for itself, but it wants some words of wisdom to accompany it
@Kristian Added a comment, it's easy to understand.
I have changed it to use the $row array only... I see the redundancy HAHA. Thanks for the answer :)
0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.