processwire / processwire-requests

ProcessWire feature requests.
40 stars 0 forks source link

Add option to preserve keys in WireArray slice method #545

Open ethnoxcom opened 1 month ago

ethnoxcom commented 1 month ago

Short description of the enhancement

Sometimes it's necessary to preserve the original keys in the WireArray result of the slice method.

Current vs. suggested behavior

Current method:

public function slice($start, $limit = 0) {
    if($limit) {
        $slice = array_slice($this->data, $start, $limit);
    } else {
        $slice = array_slice($this->data, $start);
    }
    $items = $this->makeNew();
    $items->import($slice);
    $items->setTrackChanges(true); 
    return $items; 
}

Proposed changes to the method:

public function slice($start, $limit = 0, $preserveKeys = false)
{
    if ($limit) {
        $slice = array_slice($this->data, $start, $limit);
    } else {
        $slice = array_slice($this->data, $start);
    }
    $items = $this->makeNew();
    if ($preserveKeys) {
        $items->setArray($slice);
    } else {
        $items->import($slice);
    }
    $items->setTrackChanges(true);
    return $items;
}

Why would the enhancement be useful to users?

This will improve the flexibility of the slice method and will be more aligned with PHP's array_slice method.