note 100839 added to function.array-slice

From: Date: Wed, 10 Nov 2010 14:19:31 +0000
Subject: note 100839 added to function.array-slice
Groups: php.notes 
Request: Send a blank email to php-notes+get-173909@lists.php.net to get a copy of this message
I also posted this in the explode() page, did not know where it would fit better. I needed a way to explode an array, just like one would explode a string, and could not find anything on the net. Maybe this can be made more efficient, but it fits my purpose. Contributions and comments welcome. <?php /** * Allows to explode an array into multiple arrays on a set delimiter. * Delimiter Can be set either by key, or by value, or by both (in which case, * both key and value must be strictly equal to values provided). * Note that numeric indexes don't work since the original array is reduced * at each loop (thus making numerical indexes useless). * @param array $array the array to explode * @param mixed $key the key to check * @param mixed $value the value to check * @param int $limit You can limit the number of parts with this. If set to 0, limit is infinite * @param boolean $removeDelimiter if set to TRUE, removes the delimiter key from the returned arrays * @return array|boolean an array of as many parts as needed, or FALSE on error. */ function array_explode(array $array, $key=NULL, $value=NULL, $limit=0, $removeDelimiter=TRUE){ if($key===NULL && $value===NULL){return FALSE;} $parts = array(); $delimiter = NULL; $partsN = 0; while($v = current($array)){ $k = key($array); if( (($key!==NULL && $value!==NULL) && ($k===$key && $v===$value)) || ($key!==NULL && $value===NULL && $k===$key) || ($value!==NULL && $key===NULL && $v===$value) ){ $delimiter = TRUE; if($removeDelimiter){array_shift($array);} $partsN++; if($partsN===$limit){$parts[$partsN] = $array;return $parts;} } $parts[$partsN][] = array_shift($array); } if($delimiter){ return $parts; } return FALSE; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 78.108.167.9 (proxied: 213.204.69.83) ---- Manual Page -- http://www.php.net/manual/en/function.array-slice.php Edit -- https://master.php.net/note/edit/100839 Del: integrated -- https://master.php.net/note/delete/100839/integrated Del: useless -- https://master.php.net/note/delete/100839/useless Del: bad code -- https://master.php.net/note/delete/100839/bad+code Del: spam -- https://master.php.net/note/delete/100839/spam Del: non-english -- https://master.php.net/note/delete/100839/non-english Del: in docs -- https://master.php.net/note/delete/100839/in+docs Del: other reasons-- https://master.php.net/note/delete/100839 Reject -- https://master.php.net/note/reject/100839 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#173909) next »