File: join.php

Recommend this page to a friend!
  Classes of Nathaniel Sherwood  >  Encase PHP Functional Programming  >  join.php  >  Download  
File: join.php
Role: Auxiliary script
Content type: text/plain
Description: Auxiliary script
Class: Encase PHP Functional Programming
Make functions work as if they are class functions
Author: By
Last change:
Date: 1 year ago
Size: 1,231 bytes


Class file image Download
namespace Encase\Functional;

 * Get a string by concatenting all the iterable elements, separated by a given
 * separator.
 * If `$lastSeparator` is specified, it will be used instead of `$separator` to
 * separate the last two elements in the string, or both elements if the
 * `$iterable` only has two. Can be used to build gramatically correct lists.
 * @param iterable|array $iterable
 * @param string|null $separator Used to separate sequential elements in the
 * string.
 * @param string|null $lastSeparator Used to separate the last two elements
 * in the string.
 * @return string
function join($iterable, ?string $separator = ',', string $lastSeparator = null): string
assertType($iterable, ['iterable', 'stdClass'], 'iterable');
$separator = $separator ?? ',';

    if (
$iterable instanceof \Traversable) {
$iterable = \iterator_to_array($iterable);
    } elseif (\
is_object($iterable)) {
$iterable = (array)$iterable;

    if (
$lastSeparator !== null && \count($iterable) > 1) {
$lastTwo = \array_splice($iterable, -2);
$iterable[] = \implode($lastSeparator, $lastTwo);

    return \
implode($separator, $iterable);

For more information send a message to info at phpclasses dot org.