note 100839 deleted from function.array-slice by danbrown
| From: | danbrown@php.net | Date: | Wed, 10 Nov 2010 15:08:12 +0000 |
| Subject: | note 100839 deleted from function.array-slice by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-173910@lists.php.net to get a copy of this message | ||
Note Submitter: xananax at yelostudio dot com
----
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;
}
?>