note 24684 modified in function.array-fill by felipe
| From: | felipe@php.net | Date: | Sun, 30 Dec 2007 19:33:20 +0000 |
| Subject: | note 24684 modified in function.array-fill by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-134540@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:
<?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.
http://php.net/manual/en/function.array-fill.php