Search code examples
phpsymfonycollectionsdoctrinedoctrine-collection

Get last element in Collection


I'm trying to get a property on the last element in a collection. I tried

end($collection)->getProperty()

and

$collection->last()->getProperty()

none works

(tells me I'm trying to use getProperty() on a boolean).

/**
 * Get legs
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getLegs()
{
    return $this->aLegs;
}

public function getLastlegdate()
{
    $legs = $this->aLegs;

    return $legs->last()->getStartDate();
}

Any idea why ?


Solution

  • The problem you have is due because the collection is empty. Internally the last() method use the end() php function that from the doc:

    Returns the value of the last element or FALSE for empty array.

    So change your code as follow:

    $property = null
    
    if (!$collection->isEmpty())
    {
    $property =  $collection->last()->getProperty();
    }
    

    hope this help