2

The following slices $scpar into two types one containing the first 9 and the second containing former comma separated values from 10 to 18.

$scpar9 = array_slice($scpar,0,9);
      $scpar18 = array_slice($scpar,9,18);

We then use a foreach and use an id parameter $sid to get the same comma separated value from other fields.

foreach ($scpar9 as $sid => $scpar) {

Information is then taken from other fields like this.

<b>'.$scpar.'</b> '.$sccomp[$sid].$scmen[$sid].

That all works fine, the problem is with the second 9 fields.

foreach ($scpar18 as $sid => $scpar) {
<b>'.$scpar.'</b> '.$sccomp[$sid].$scmen[$sid].

The field $scpar is correct but the ones containing the [$sid] are starting from the first result not the 9th.

Any ideas?

Marvellous

2
  • why are you slicing these into 2 arrays? wouldn't a for loop be better? Commented Jul 18, 2011 at 13:20
  • Can you explain to me how that works Commented Jul 18, 2011 at 13:21

3 Answers 3

1

you need to use preserve_keys

preserve_keys : Note that array_slice() will reorder and reset the array indices by default. You can change this behaviour by setting preserve_keys to TRUE.

   $scpar18 = array_slice($scpar,9,18, true);
0
1

If you want to preserve the keys ($sid), you need to set the fourth param to true for array_slice, see http://php.net/manual/en/function.array-slice.php

1

array_slice() creates new arrays containing the values from the original arrays, not the keys. Using the keys in the foreach loop is meaningless in the context of the original array, since these are the keys from the new slice arrays.

Use array_slice($scpar, 9, 18, true) to copy the keys as well, not just the values:

$scpar18 = array_slice($scpar, 9, 18, true);
                                  #    ^^^ preserve keys

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.