QRdvark.com

Ever needed to re-index an array from a number that is not zero. Here is a simple helper function to get you through what can be a difficult time. If you simply needed to re-index the array beginning at zero, array_values() is the function you are looking for. If you wish to begin at one or even eighty eight, as in the example below, this is the way to go about it.


<?php

/**
 *
 * Function to re-index an array beginning at N
 *
 * @param array $array
 *
 * @param int $start
 *
 * @return @array
 *
 */
 
function reIndex($start$array)
 {
    
/*** the end number of keys minus one ***/
    
$end = ($start+count($array))-1;

    
/*** the range of numbers to use as keys ***/
    
$keys range($start$end);

    
/*** combine the arrays with the new keys and values ***/
    
return array_combine($keys$array);
 }

  
/*** an array of native australians ***/
  
$animals = array("koala""kangaroo""platypus""dingo""wombat""steve irwin""wallaby");

  
/*** re-index the array ***/
  
$newArray reIndex(88$animals);

  
/*** show the new array keys and values ***/
  
foreach($newArray as $key=>$value)
 {
    echo 
$key." -- ".$value."<br />";
 }
?>