php – How to know I'm in the first cycle of fetchArray() loop-ThrowExceptions

Exception or error:

I want to print an attribute (i.e. active) on the first element of an array.
The ugly way is to use a variable:

<ul class="nav nav-pills">
    <?php $firstItem = true; ?>
    <?php while ($row = $res_sections->fetchArray()) { ?>
    <li class="nav-item">
        <a class="nav-link<?php if ($firstItem) echo ' active' ?>" data-toggle="pill" href="#nav<?= $row['section']?>"><?php echo "{$row["section"]}"?></a>
    <?php $firstItem = false; ?>
    <?php } ?>      

I wonder if there’s something more elegant.
Is there a way to know if $row is the first element (or any) of the fetchArray() result?


Here where fetchArray() comes from:

$db = new SQLite3("/db.sqlite");
$sql_sections = "SELECT DISTINCT section FROM settings";
$res_sections = $db->query(SQLite3::escapeString($sql_sections));
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *