$key starting with 1

Asked

Viewed 112 times

0

Good afternoon guys, as I start a $key from a foreach for 1?

foreach ($dados as $key => $reg) {
$table .= '<tr>
           <td width="3%">' . $key . '</td>
           <td width="18%">' . $reg['nome_clientet'] . '</td>
</tr>';

It’s starting at zero, I’d like to start from '1';

2 answers

1


It seems that 1 would be more in the display as it is putting in the table so using a +1 would solve the print.

foreach ($dados as $key => $reg) {
    $newKey = $key +1;
    $table .= '<tr>
           <td width="3%">' . $newKey . '</td>
           <td width="18%">' . $reg['nome_clientet'] . '</td>
</tr>';

Soon, you would use the $newKey in the prints and the $key in the backend.

Or for the array to actually start from scratch it should work like this:

array_push($array[0], $array); #adiciona o primeiro elemento como ultimo (para nao perder dados)
unset($array[0]); #apaga primeiro elemento do array.
  • 1

    That’s right, man. Thank you very much.

0

You can crop the array first before entering the foreach.

$reg = array_slice($reg, 1);
foreach ($dados as $key => $reg) {
    $table .= '<tr>
           <td width="3%">' . $key . '</td>
           <td width="18%">' . $reg['nome_clientet'] . '</td>
    </tr>';
  • 1

    remove the first result will not cause data loss?

  • It doesn’t work that way Euler

Browser other questions tagged

You are not signed in. Login or sign up in order to post.