Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 920
Pierre Olivier Tran Avatar asked Sep 10 '15 16:09

Pierre Olivier Tran


1 Answers

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

like image 110
Matteo Avatar answered Sep 30 '22 17:09

Matteo