santa
santa

Reputation: 12512

Starting array index with 1 instead of 0

I have a script that outputs results into an array via a foreach loop:

foreach ($export AS $exp) {
    $_SESSION['export'][] = array($exp->label, $exp->pos_X, $exp->pos_Y);
}

It works great however the count starts with 0 and results look odd:

0   Value1    34      52
1   Value2   -12      66
2   ValueX    20      47
3   ValueZ   -22      94

I'd like it to be

1   Value1    34      52
2   Value2   -12      66
3   ValueX    20      47
4   ValueZ   -22      94

How can I fix that?

Upvotes: 0

Views: 2023

Answers (1)

Sahil Gulati
Sahil Gulati

Reputation: 15141

If you don't want to alter value of key with +1 at the time of displaying, then maintain a counter variable $x which starts from 1 and keep on incrementing it in loop.

<?php
ini_set('display_errors', 1);
$x=1;
foreach ($export AS $exp) 
{
     $_SESSION['export'][$x] = array($exp->label, $exp->pos_X, $exp->pos_Y);
     $x++;//added this line for incrementing value of $x
}

Upvotes: 1

Related Questions