In this post, I will focus on the Laravel collection flip example. I will provide you with a simple example of how to use collection flip Laravel. The flip method is used to swap the keys and values of an array within a collection.
The flip() method will return a new collection instance where all the collection item’s keys have been exchanged with their corresponding values.
What is the flip() method?
- Swapping keys with values in a Laravel collection.
- It is particularly useful when transforming associative arrays or mapping values for quick lookups.
Let’s see an example of using the Laravel collection flip method below.
Syntax:
$collection->flip();
Laravel collection flip() example
Example 1:
public function index()
{
$collection = collect([
1 => 'First',
2 => 'Second',
3 => 'Second',
4 => 'Fourth'
]);
$flipCollection = $collection->flip();
dd($flipCollection);
}
Output:
#items: array:4 [▼
"First" => 1
"Second" => 2
"Third" => 3
"Fourth" => 4
]
Example 2: Handling Duplicate values in collection
Explain that when values are duplicated, keys from the original collection might be overwritten.
$collection = collect(['a' => 1, 'b' => 1, 'c' => 2]);
$flippedCollection = $collection->flip();
dd($flippedCollection);
Output:
#items: array:2 [▼
1 => "b"
2 => "c"
]
The last key b overwrites the first one a.
Read also: Laravel collection sortByDesc example
I hope this tutorial help you.