How will you get first and last item from the collection in Magento?

$collection->getFirstItem() and $collection->getLastItem();

In Magento, you can get the first and last items from a collection using various methods depending on the context and type of collection. Here are some common approaches:

  1. Using getFirstItem() and getLastItem() methods:
    php
    // Assuming $collection is your collection object
    $firstItem = $collection->getFirstItem();
    $lastItem = $collection->getLastItem();
  2. Using array access for the collection:
    php
    // Assuming $collection is your collection object
    $firstItem = $collection->getFirstItem();
    $lastItem = $collection->getLastItem();
  3. Using getFirstItem() and getLastItem() via ->getItems() method:
    php
    // Assuming $collection is your collection object
    $firstItem = $collection->getItems();
    $firstItem = reset($firstItem); // First item
    $lastItem = end($firstItem); // Last item
  4. Using direct access to collection items:
    php
    // Assuming $collection is your collection object
    $firstItem = $collection->getFirstItem();
    $lastItem = $collection->getLastItem();
  5. Using array access by keys:
    php
    // Assuming $collection is your collection object
    $items = $collection->getItems();
    $firstItem = reset($items);
    $lastItem = end($items);

These are some of the common methods to retrieve the first and last items from a Magento collection. The specific method you choose may depend on the context of your code and your preference for readability and efficiency.