note 100838 added to function.explode

From: Date: Wed, 10 Nov 2010 14:18:07 +0000
Subject: note 100838 added to function.explode
Groups: php.notes 
Request: Send a blank email to php-notes+get-173908@lists.php.net to get a copy of this message
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.explode.php Edit -- https://master.php.net/note/edit/100838 Del: integrated -- https://master.php.net/note/delete/100838/integrated Del: useless -- https://master.php.net/note/delete/100838/useless Del: bad code -- https://master.php.net/note/delete/100838/bad+code Del: spam -- https://master.php.net/note/delete/100838/spam Del: non-english -- https://master.php.net/note/delete/100838/non-english Del: in docs -- https://master.php.net/note/delete/100838/in+docs Del: other reasons-- https://master.php.net/note/delete/100838 Reject -- https://master.php.net/note/reject/100838 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#173908) next »