0

I have a feeling I'm going to get scolded for this but here is the question.

$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number) 
{
    Bullet <?php echo $seq_number;?>  
    // (this successfully creates - Bullet 1, Bullet 2, etc. - 
        below is the problem.

    <?php echo $db_rs['bullet_($seqnumber)'];?>
}   // this one doesn't work.  

I've tried with curly brackets {}

I basically have a few columns that are named same except for number at the end (bullet_1, bullet_2, bullet_3, etc.) and want to get the results using a loop.

1
  • 1
    The given code would probably give a syntax error. Using PHP tags withing PHP tags just makes no sense. Commented Jan 18, 2013 at 8:30

4 Answers 4

5

Your problem is, that PHP doesn't replace variables inside strings enclosed with single quotes. You need to use $db_rs["bullet_{$seq_number}"] or one of those:

<?php
foreach ($seq_numbers as $seq_number) {
   $key = 'bullet_' . $seq_number;
   echo $db_rs[$key];
}

Even shorter, but a little less clear:

<?php
foreach ($seq_numbers as $seq_number) {
   echo $db_rs['bullet_' . $seq_number];
}

An entirely different approach would be to loop over the result array. Then you don't even need $seq_numbers. Just as an afterthought.

<?php
foreach ($db_rs as $key => $value) {
   if (substr($key, 0, 7) == 'bullet_') {
      echo $value;
   }
}

Oh...and watch out for how you spell your variables. You are using $seq_number and $seqnumber.

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

1 Comment

This is a very detailed explanation. Now I completely understand it! I hate asking questions where the answer is there but I don't quite understand. Thank you! Another tool in the belt.
1
<?php echo $db_rs['bullet_'.$seqnumber];?>

Comments

1

why not:

$db_rs['bullet_'.$seqnumber]

If not, what are your fields, and what does a var_dump of $db_rs look like?

Comments

0

try this...

$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number) 
{
    Bullet <?php echo $seq_number;?>  
    // (this successfully creates - Bullet 1, Bullet 2, etc. - 
        below is the problem.

    <?php echo $db_rs["bullet_($seqnumber)"];?>
}   // now it works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.