Laravel Collection Public API: keys

November 29, 2016 —John Koster

keys

The keys method is used to retrieve the keys of all items in the collection. The keys method returns a new Collection instance.

The following code example demonstrates the usage of the keys method:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection.
6$collection = new Collection([
7 'first', 'second', 'third'
8]);
9 
10$keys = $collection->keys();

After the above code executes, the $keys variable would contain a value similar to the following output:

1object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=3)
4 0 => int 0
5 1 => int 1
6 2 => int 2

The following shows a sample, with output, of a collection containing items represented by an associative array:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection.
6$collection = new Collection([
7 'first' => 'I am first',
8 'second' => 'I am second',
9 'third' => 'I am third'
10]);
11 
12$keys = $collection->keys();

The $keys variable would now contains a value similar to the following output:

1object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=3)
4 0 => string 'first' (length=5)
5 1 => string 'second' (length=6)
6 2 => string 'third' (length=5)

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.