Skip to content

IEnumerable.single() method

Marcel Kloubert edited this page Sep 25, 2015 · 3 revisions

IEnumerable->single([$predicate]) method

Returns the one and only element of the sequence (s. Single()).

An exception is thrown, if more than one element was found or no element was found.

Syntax

public function single([ predciate $predicate = null ]]) : mixed;

Parameters

Name Type Description
$predicate [[predicate Predicate]]

$predicate

The custom predciate to use.

Result

The one and only value of the sequence.

Examples

Default

use \System\Collections\ElementNotFoundException;
use \System\Collections\EnumerableException;
use \System\Linq\Enumerable;

$seq1 = Enumerable::fromValues(11);
$seq2 = Enumerable::fromValues();
$seq3 = Enumerable::fromValues(1, 2);

// 11
$val1 = $seq1->single();

try {
    $val2 = $seq2->single();
}
catch (ElementNotFoundException $ex) {
    // code goes here
}

try {
    $val3 = $seq3->single();
}
catch (EnumerableException $ex) {
    // the code should be go here
    $thrownEx = $ex;
}

// (true)
$is1 = isset($thrownEx) && 
       ($thrownEx instanceof EnumerableException);
// (false)
$is2 = isset($val3);

Predicate (lambda)

use \System\Collections\ElementNotFoundException;
use \System\Collections\EnumerableException;
use \System\Linq\Enumerable;

$seq1 = Enumerable::fromValues(11);
$seq2 = Enumerable::fromValues(10, 11);
$seq3 = Enumerable::fromValues(9, 10, 11);

$predicate = '$x => $x < 11';

try {
    $val1 = $seq1->single($predicate);
}
catch (ElementNotFoundException $ex) {
    // code goes here
}

// 10
$val2 = $seq2->single($predicate);

try {
    $val3 = $seq3->single($predicate);
}
catch (EnumerableException $ex) {
    // the code should be go here
    $thrownEx = $ex;
}

// (true)
$is1 = isset($thrownEx) && 
       ($thrownEx instanceof EnumerableException);
// (false)
$is2 = isset($val3);

Predicate (closure)

use \System\Collections\ElementNotFoundException;
use \System\Collections\EnumerableException;
use \System\Linq\Enumerable;

$seq1 = Enumerable::fromValues(11);
$seq2 = Enumerable::fromValues(10, 11);
$seq3 = Enumerable::fromValues(9, 10, 11);

$predicate = function ($x) {
                 return $x < 11;
             };

try {
    $val1 = $seq1->single($predicate);
}
catch (ElementNotFoundException $ex) {
    // code goes here
}

// 10
$val2 = $seq2->single($predicate);

try {
    $val3 = $seq3->single($predicate);
}
catch (EnumerableException $ex) {
    // the code should be go here
    $thrownEx = $ex;
}

// (true)
$is1 = isset($thrownEx) && 
       ($thrownEx instanceof EnumerableException);
// (false)
$is2 = isset($val3);
Clone this wiki locally