By 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.
#Signature
1public function keys();
#Example Use
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 array
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:
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 array
4 0 => string 'first'
5 1 => string 'second'
6 2 => string 'third'
∎