note 41347 modified in function.array-chunk by aidan

From: Date: Thu, 03 Jun 2004 10:16:04 +0000
Subject: note 41347 modified in function.array-chunk by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-70420@lists.php.net to get a copy of this message
For those of you that need array_chunk() for PHP < 4.2.0, this function should do the trick: <?php if (!function_exists('array_chunk)')) { function array_chunk( $input, $size, $preserve_keys = false) { @reset( $input ); $i = $j = 0; while( @list( $key, $value ) = @each( $input ) ) { if( !( isset( $chunks[$i] ) ) ) { $chunks[$i] = array(); } if( count( $chunks[$i] ) < $size ) { if( $preserve_keys ) { $chunks[$i][$key] = $value; $j++; } else { $chunks[$i][] = $value; } } else { $i++; if( $preserve_keys ) { $chunks[$i][$key] = $value; $j++; } else { $j = 0; $chunks[$i][$j] = $value; } } } return $chunks; } } ?> --was-- Above code needs a little correction, because the keys are not preserved, in the code beneath they are. <?php if (!function_exists('array_chunk)')) { function array_chunk( $input, $size, $preserve_keys = FALSE ) { @reset( $input ); $i = $j = 0; while( @list( $key, $value ) = @each( $input ) ) { if( !( isset( $chunks[$i] ) ) ) { $chunks[$i] = array(); } if( count( $chunks[$i] ) < $size ) { if( $preserve_keys ) { $chunks[$i][$key] = $value; $j++; } else { $chunks[$i][] = $value; } } else { $i++; if( $preserve_keys ) { $chunks[$i][$key] = $value; $j++; } else { $j = 0; $chunks[$i][$j] = $value; } } } return $chunks; } } ?> http://www.php.net/manual/en/function.array-chunk.php

« previous php.notes (#70420) next »