April 22, 2018 —John Koster
The keys
method is used to retrieve the keys of all items in the collection. The keys
method returns a new Collection
instance.
The behavior of the keys
method is similar to PHP's array_keys
function.
1public function keys();
The following code example demonstrates the usage of the keys
method:
1use Illuminate\Support\Collection;2 3// Create a new collection.4$collection = new Collection([5 'first', 'second', 'third'6]);7 8$keys = $collection->keys();
After the above code executes, the $keys
variable would contain a value similar to the following output:
1object(Illuminate\Support\Collection)2 protected 'items' =>3 array4 0 => int 05 1 => int 16 2 => int 2
The following shows a sample, with output, of a collection containing items represented by an associative array:
1use Illuminate\Support\Collection; 2 3 4// Create a new collection. 5$collection = new Collection([ 6 'first' => 'I am first', 7 'second' => 'I am second', 8 'third' => 'I am third' 9]);10 11$keys = $collection->keys();
The $keys
variable would now contains a value similar to the following output:
1object(Illuminate\Support\Collection)2 protected 'items' =>3 array4 0 => string 'first'5 1 => string 'second'6 2 => string 'third'
∎
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.