Illuminate\Support\Collection::every PHP Method

every() public method

Create a new collection consisting of every n-th element.
public every ( integer $step, integer $offset ) : static
$step integer
$offset integer
return static
    public function every($step, $offset = 0)
    {
        $new = [];
        $position = 0;
        foreach ($this->items as $item) {
            if ($position % $step === $offset) {
                $new[] = $item;
            }
            $position++;
        }
        return new static($new);
    }

Usage Example

Example #1
0
 public function testEvery()
 {
     $data = new Collection([6 => 'a', 4 => 'b', 7 => 'c', 1 => 'd', 5 => 'e', 3 => 'f']);
     $this->assertEquals(['a', 'e'], $data->every(4)->all());
     $this->assertEquals(['b', 'f'], $data->every(4, 1)->all());
     $this->assertEquals(['c'], $data->every(4, 2)->all());
     $this->assertEquals(['d'], $data->every(4, 3)->all());
 }