PHP Classes

File: first.php

Recommend this page to a friend!
  Classes of Nathaniel Sherwood   Encase PHP Functional Programming   first.php   Download  
File: first.php
Role: Example script
Content type: text/plain
Description: Example script
Class: Encase PHP Functional Programming
Make functions work as if they are class functions
Author: By
Last change:
Date: 5 years ago
Size: 950 bytes
 

Contents

Class file image Download
<?php
namespace Encase\Functional;

/**
 * Get the value of the first element in `$iterable`.
 *
 * @param \Traversable|iterable|string|stdClass|null
 * @return mixed|null The first element in `$iterable` or null if empty.
 */
function first($iterable)
{
   
$type = assertType($iterable, ['\Traversable', 'iterable', 'string', 'stdClass', 'null'], 'iterable');

    if (empty(
$iterable)) {
        return
null;
    }

    if (
$type === 'string') {
        return \
mb_substr($iterable, 0, 1);
    }

   
// Account for external iterators.
   
if ($iterable instanceof \IteratorAggregate) {
       
$iterable = $iterable->getIterator();
    }

   
// Ensure iterators are valid so we return null rather than false like
    // end() does. If it's an \ArrayIterator, we can treat it as an array, for
    // whatever reason...
   
if ($iterable instanceof \Iterator) {
        if (!
$iterable->valid()) {
            return
null;
        }

       
$iterable->rewind();
        return
$iterable->current();
    }

    return \
reset($iterable);
}