note 21773 modified in function.array-splice by vrana

From: Date: Tue, 17 Aug 2004 14:50:03 +0000
Subject: note 21773 modified in function.array-splice by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-80032@lists.php.net to get a copy of this message
I believe the following is a version of array_slice that solves most of the issues for people that want an associative key offset, rather than an integer. <?php function key_array_splice(&$input, $key_ofs, $length=NULL, $replacement=NULL) { // Adjust the length if it was negative or not passed if($length===NULL || $length<0) $count = $length+count($input); // Cycle through the array foreach($input as $key=>$value){ if(!$key_found){ if($key===$key_ofs){ $key_found=true; if($length!==NULL && $length>=0) $count=$length; if(is_array($replacement)) foreach($replacement as $r_key=>$r_value) $new_array[$r_key]=$r_value; }else $new_array[$key]=$value; } if($key_found){ if($count>0) $ret_array[$key]=$value; else $new_array[$key]=$value; } $count--; } // Finish up $input=$new_array; return $ret_array; } ?> Note that this code needs PHP 4 for the use of the "===" and "!==" operators. --was-- I believe the following is a version of array_slice that solves most of the issues for people that want an associative key offset, rather than an integer. function key_array_splice(&$input, $key_ofs, $length=NULL, $replacement=NULL) { // Adjust the length if it was negative or not passed if($length===NULL || $length<0) $count = $length+count($input); // Cycle through the array foreach($input as $key=>$value){ if(!$key_found){ if($key===$key_ofs){ $key_found=true; if($length!==NULL && $length>=0) $count=$length; if(is_array($replacement)) foreach($replacement as $r_key=>$r_value) $new_array[$r_key]=$r_value; }else $new_array[$key]=$value; } if($key_found){ if($count>0) $ret_array[$key]=$value; else $new_array[$key]=$value; } $count--; } // Finish up $input=$new_array; return $ret_array; } Note that this code needs PHP 4 for the use of the "===" and "!==" operators. http://php.net/manual/en/function.array-splice.php

« previous php.notes (#80032) next »