0

I have the following code to retrieve the results to an image carousel, but I need to add an "active" class on the first div. How do i proceed?

$var = explode(',',$rRow["meta_images"]);
foreach($var as $row)
{
  echo '<div class="item">
  <img src="'.$row.'">
  </div>';
}

The result should look like this:

<div class="item active">
</div>

<div class="item">
</div>

<div class="item">
</div>

3 Answers 3

2

Toss in a simple counter. Start at 0 and increment at the end of the foreach loop. Check for when the counter is 0. That will match the first time.

$var = explode(',',$rRow["meta_images"]);
$i = 0;
foreach($var as $row)
{
  $active = ($i === 0) ? ' active' : '';
  echo '<div class="item'.$active.'">
  <img src="'.$row.'">
  </div>';
  $i++;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Use a for loop -

$var = explode(',',$rRow["meta_images"]);
for($i = 0; $i < count($var); $i++)
{
  if(0 == $i)
    {
        echo '<div class="active item">';
    }
    else 
    {
        echo '<div class="item">';
    }
    echo '<img src="'.$var[$i].'"></div>';
}

Comments

2
$var = explode(',',$rRow["meta_images"]);
foreach($var as $key => $row)
{
  if($key == 0) $active = "active";
  else $active = '';
  echo '<div class="'.$active.' item">
  <img src="'.$row.'">
  </div>';
}

1 Comment

@JayBlanchard Right, my bad, fixed it.

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.