Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
 
why are you slicing these into 2 arrays? wouldn't a for loop be better? –  Daniel A. White Jul 18 '11 at 13:20
 
Can you explain to me how that works –  Robin Knight Jul 18 '11 at 13:21
add comment

3 Answers

up vote 0 down vote accepted

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);
share|improve this answer
 
Well done ...... –  Robin Knight Jul 18 '11 at 15:09
add comment

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

share|improve this answer
add comment

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.