Normally when I vote to close a question as duplicate, I will not post an answer, but there are several opportunities to educate on this question that are difficult to delineate in mere comments.
It is vital, if you are going to increment in the echo line, that the ++
comes before $i
. If the ++
comes after $i
, then the initial value of $i
is echoed THEN the incrementation occurs.
Assuming I've got the structure of your resultset right, this is how I would write the snippet:
Code: (Demo)
$sql=[
(object)['jobseeker_name'=>'A','jobseeker_phone'=>'B','login_email'=>'C'],
(object)['jobseeker_name'=>'D','jobseeker_phone'=>'E','login_email'=>'F'],
(object)['jobseeker_name'=>'G','jobseeker_phone'=>'H','login_email'=>'I']
];
foreach($sql as $i=>$row){
echo "<tr>";
echo "<td>",++$i,"</td>";
echo "<td>$row->jobseeker_name</td>";
echo "<td>$row->jobseeker_phone</td>";
echo "<td>$row->login_email</td>";
echo "</tr>";
}
Output:
<tr>
<td>1</td>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td>2</td>
<td>D</td>
<td>E</td>
<td>F</td>
</tr>
<tr>
<td>3</td>
<td>G</td>
<td>H</td>
<td>I</td>
</tr>
Additionally, as a matter of best practice:
Use a new variable name to distinguish each row of the $sql
array of objects. If you use foreach($sql as $sql){
then if you need to access $sql
again, you will only be able to access the last iterated subarray of $sql
This is because the foreach loop is constantly overwriting the input array.
Use commas rather than dots to concatenate with echo. It is a nano-optimization, but there is no downside to doing this a matter of habit.
Also as a matter of nano-optimization, it is faster to use "pre-incrementation" (++$i
) rather than "post-incrementation" ($i++
) in all cases where the outcome is the same. What's the difference between ++$i and $i++ in PHP?