How to search for an element in a collection and get its index in illuminate/collections?

In Illuminate/Collections, you can use the search() method to find an element in a collection and retrieve its index.

Here's an example:

use Illuminate\Support\Collection; $collection = collect([2, 4, 6, 8, 10]); $index = $collection->search(6); // The search() method will return the index if the element is found // or false if the element is not present in the collection. if ($index !== false) { echo "The element 6 is found at index: " . $index; } else { echo "The element 6 is not present in the collection."; }

Output:

The element 6 is found at index: 2

If the element is not found, the search() method will return false, which allows you to handle cases where the element is not present in the collection.