note 24684 modified in function.array-fill by vrana

From: Date: Tue, 17 Aug 2004 13:57:50 +0000
Subject: note 24684 modified in function.array-fill by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-80004@lists.php.net to get a copy of this message
array_fill() cannot be used to setup only missing keys in an array. This may be necessary for example before using implode() on a sparse filled array. The solution is to use this function: <?php function array_setkeys(&$array, $fill = NULL) {   $indexmax = -1;   for (end($array); $key = key($array); prev($array)) {     if ($key > $indexmax)       $indexmax = $key;   }   for ($i = 0; $i <= $indexmax; $i++) {     if (!isset($array[$i]))       $array[$i] = $fill;   }   ksort($array); } ?> This is usefull in some situations where you don't know which key index was filled and you want to preserve the association between a positioned field in an imploded array and the key index when exploding it. --was-- array_fill() cannot be used to setup only missing keys in an array. This may be necessary for example before using implode() on a sparse filled array. The solution is to use this function: function array_setkeys(&$array, $fill = NULL) {   $indexmax = -1;   for (end($array); $key = key($array); prev($array)) {     if ($key > $indexmax)       $indexmax = $key;   }   for ($i = 0; $i <= $indexmax; $i++) {     if (!isset($array[$i]))       $array[$i] = $fill;   }   ksort($array); } This is usefull in some situations where you don't know which key index was filled and you want to preserve the association between a positioned field in an imploded array and the key index when exploding it. http://php.net/manual/en/function.array-fill.php

« previous php.notes (#80004) next »