-4

I have this function that gives a specific number to every item of a loop.

<?php $counter =0; ?>
<?php while( have_rows('profs_associes') ): the_row(); ?>
  <?php
    ++$counter; 
    if($counter == 1) {$imageclass = 'data-contentid="1"';}
    if($counter == 2) {$imageclass = 'data-contentid="2"';}
    if($counter == 3) {$imageclass = 'data-contentid="3"';}
    if($counter == 4) {$imageclass = 'data-contentid="4"';}
    if($counter == 5) {$imageclass = 'data-contentid="5"';}
    if($counter == 6) {$imageclass = 'data-contentid="6"';}
    if($counter == 7) {$imageclass = 'data-contentid="7"';}
    if($counter == 8) {$imageclass = 'data-contentid="8"';}
    if($counter == 9) {$imageclass = 'data-contentid="9"';}
    if($counter == 10) {$imageclass = 'data-contentid="10"';}
?>
<div class="img-row" <?php echo $imageclass; ?>>

But it seems it could be simplified (I have to do a lot of it) by simply writing one function that sets the number of the item as a the 'id' of said item. Can anybody help ?

  • See if this give you any ideas: http://stackoverflow.com/questions/4676417/should-i-use-curly-brackets-or-concatenate-variables-within-strings – mustaccio Apr 20 '14 at 22:17
  • Please explain more specifically what you're trying to accomplish and what the problem is. Please read this advice on how to [ask] good questions and Jon Skeet's blog post [Writing the perfect question](http://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx). Pay special attention to the "Golden Rule", though I highly advise you to read the entire article. – Adi Inbar Apr 21 '14 at 00:53

3 Answers3

0
++$counter; 
$imageclass = 'data-contentid="'.$counter.'"';

I believe this is what you are trying to do. The . operator concatenates the value of $counter to the string.

wavemode
  • 2,076
  • 1
  • 19
  • 24
0

Just assign the value of the counter into the relevant place:

<?php while( have_rows('profs_associes') ): the_row(); ?>
  <?php
    ++$counter; 
    $imageclass = 'data-contentid="'.$counter.'"';
Royal Bg
  • 6,988
  • 1
  • 18
  • 24
0

You have a lot of open and close php tags, you dont need do that (at all actually).

<?php
$counter =0;
while( have_rows('profs_associes') ): the_row();// Not really sure what's going on here
    ++$counter; 
    $imageclass = 'data-contentid="'.$counter.'"';
    echo '<div class="img-row" '.$imageclass.'>':
}
?>

You could minimize even further:

<?php
$counter =0;
while( have_rows('profs_associes') ): the_row(); 
    echo '<div class="img-row" data-contentid="'.(++$counter).'">':
}
?>

And if you only want to loop 10 times, we have the for():

<?php
for($counter=1; $count<=10; $counter++){
    echo '<div class="img-row" data-contentid="'.$counter.'">':
}
?>
Martijn
  • 15,791
  • 4
  • 36
  • 68