0

I want to convert my for loop to a foreach loop but i am confused.I always write wrong code .

my for loop

$cd = $c->Select();
if($cd>0)
{
    $sl=1;
    for($i = 0; $i < count($cd); $i++)
    {
        print '<td>'.$sl++.'</td>';
        print '<td>'.$cd[$i][1].'</td>';
        print '<td>'.$cd[$i][2].'</td>';
    }
}
1
  • Can you include your attempt at the foreach loop? You'll be more likely to get a good answer more quickly if you do. Commented Feb 23, 2014 at 15:36

2 Answers 2

2
foreach($cd as $item)
{
  print '<td>'.$sl++.'</td>';
  print '<td>'.$item[1].'</td>';
  print '<td>'.$item[2].'</td>';
}

Example

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

Comments

0

You can loop in your $cd array as follow

$sl = 1;
foreach($cd as $data)
{
    print '<td>'.$sl++.'</td>';
    print '<td>'.$data[1].'</td>';
    print '<td>'.$data[2].'</td>';
}

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.