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?

2
  • 5
    arrays are zero index. If you want it to start at 1, add +1 to the original index Commented Apr 19, 2017 at 16:10
  • 2
    What results "look odd"? Are you talking about the value $SESSION['export'] (why is it important what it "looks like"?) or somewhere that its value is displayed to the user? Commented Apr 19, 2017 at 16:10

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

5 Comments

@santa The next programmer that picks up this code is going to punch someone... Are you going to do this for everyone of your arrays?
@nerdlyist can i ask you why? in my post i just gave an alternative.
Mostly for the guy that accepted this. This is overhead, inconsistent and prone to causing error when someone doesn't know what is going on. Your answer is 100% correct just solving something that does not need to be
@nerdlyist Please look into first line of my post, from my side i tried to explain you can change your key by incrementing one and if you dont want it to be done. then choose my solution.
I get it an I did not down vote but people looking at this should know it is a bad idea.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.