note 44167 modified in function.array-splice by tomsommer
| From: | tomsommer@php.net | Date: | Fri, 16 Jul 2004 17:31:31 +0000 |
| Subject: | note 44167 modified in function.array-splice by tomsommer | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-73405@lists.php.net to get a copy of this message | ||
This function will preserve keys:
function my_array_splice(&$_arr, $_index, $_long){
$_keys=array_keys($_arr);
$_key=array_search($_index, $_keys);
if ( $_key !== FALSE ){
$_keys=array_splice($_keys, $_key, $_long);
foreach ($_keys as $_key) unset($_arr[$_key]);
}
}
--was--
Concerning the note from:
"plyrvt at mail dot ru (Yura Pylypenko)"
"07-Aug-2003 02:36"
You function is indeed nice but has a flaw. When you do not find the element searched for $_key is
false but will be interpreted as 0 hence your function will delete the first value of the array.
So check is value of $_key is "FALSE" or 0 (in the case the first element is the one to be
deleted:
function my_array_splice(&$_arr, $_index, $_long){
$_keys=array_keys($_arr);
$_key=array_search($_index, $_keys);
if ( $_key !== FALSE ){
$_keys=array_splice($_keys, $_key, $_long);
foreach ($_keys as $_key) unset($_arr[$_key]);
}
}
Now it works fine.
Best regards, Richard
http://php.net/manual/en/function.array-splice.php