Reputation: 2004
So I have a table which is generated by a foreach loop. Within the table the id is used to load a modal. I wonder how I can generate a numircal sequence starting from 1, then 2, 3 and so on. I am aware that I can use http://www.php.net/manual/en/function.sprintf.php for this, but I don´t know how to use is within the existing loop? I have market the placement within the code with ????
The reason I want to do this is to add some structure for the reader, it will have no other function.
code:
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>#</th>
<th>Fråga:</th>
</tr>
</thead>
<tbody>
<?php foreach ($modals as $key => $title) { ?>
<tr>
<td><?php ???? ?></td>
<td><a href="#cptmodal_<?php echo $title['id']; ?>" data-toggle="modal"><?php echo $title['title'];?></a></td>
</tr>
<?php } ?>
</tbody>
</table>
Upvotes: 0
Views: 424
Reputation: 3204
I think this is what you are looking for. There are tons of ways to do it though.
<?php $i = 0; ?>
<?php foreach ($modals as $key => $title): ?>
<?php $i++; ?>
<tr>
<td><?php echo $i; ?></td>
<td><a href="#cptmodal_<?php echo $title['id']; ?>" data-toggle="modal"><?php echo $title['title'];?></a></td>
</tr>
<?php endforeach; ?>
Edit: You do not use the $key
at all, you can just use a for
loop, makes for cleaner code.
<?php for($i = 0; $i < count($modals); $i++): ?>
<tr>
<td><?php echo $i; ?></td>
<td><a href="#cptmodal_<?php echo $modals[$i]['id']; ?>" data-toggle="modal"><?php echo $modals[$i]['title'];?></a></td>
</tr>
<?php endfor; ?>
EDIT: Depending on the structure of your array you can use the $key
; ie. if it looks like this:
$modals = array(
0 => array('id' => $id, 'title' => $title),
1 => array('id' => $id, 'title' => $title),
2 => array('id' => $id, 'title' => $title),
);
<?php foreach ($modals as $key => $title): ?>
<tr>
<td><?php echo $key + 1; /* Note the +1 here (arrays start from 0) */ ?></td>
<td><a href="#cptmodal_<?php echo $title['id']; ?>" data-toggle="modal"><?php echo $title['title'];?></a></td>
</tr>
<?php endforeach; ?>
Upvotes: 5
Reputation: 1065
<?php int $i = 1; foreach ($modals as $key => $title) { ?>
<tr>
<td><?php echo($i); $i++; ?></td>
<td><a href="#cptmodal_<?php echo $title['id']; ?>" data-toggle="modal"><?php echo $title['title'];?></a></td>
</tr>
<?php } ?>
Upvotes: 3