-
-
Notifications
You must be signed in to change notification settings - Fork 13
IEnumerable.firstOrDefault() method
Marcel Kloubert edited this page Sep 25, 2015
·
3 revisions
Returns the first element of the sequence, or a default value if no element was found (s. FirstOrDefault()).
public function firstOrDefault([mixed $predicateOrDefaultValue
[, mixed $defValue]]) : mixed;
Name | Type | Description |
---|---|---|
$predicateOrDefaultValue | [[predicate | Predicate]]|mixed |
$defValue | mixed | [OPTIONAL] The value to return if no matching element was found. DEFAULT value is NULL
|
If it is a callable, the predicate has the following structure:
function (mixed $item, IIndexedItemContext $ctx) : bool;
The current item.
The current item context.
Is returned if no element was found / sequence is empty.
The first value of the sequence or the default value.
use \System\Linq\Enumerable;
$seq1 = Enumerable::fromValues(5979, 'TM', 7.7);
$seq2 = Enumerable::fromValues();
// 5979
$a1 = $seq1->firstOrDefault();
// (false)
$a2 = $seq2->firstOrDefault(false);
use \System\Linq\Enumerable;
$seq1 = Enumerable::fromValues(5979.0, 'TM', 5979, 66.6);
$seq2 = Enumerable::fromValues();
$predicate = '$x => $x == 5979';
// 5979.0
$a1 = $seq1->firstOrDefault($predicate);
// (false)
$a2 = $seq2->firstOrDefault($predicate, false);
use \System\Linq\Enumerable;
$seq1 = Enumerable::fromValues(5979.0, 'TM', 5979, 66.6);
$seq2 = Enumerable::fromValues();
$predicate = function($x) {
return $x === 5979;
};
// 5979
$a1 = $seq1->firstOrDefault($predicate);
// (false)
$a2 = $seq2->firstOrDefault($predicate, false);