S
S
Shimpanze2021-08-12 13:25:43
PHP
Shimpanze, 2021-08-12 13:25:43

Shortest way to process each element of an array?

A question for professional development.

Is there a more concise way to add dots (just for example) before each array element?

I use this one, but suddenly the pros use a shorter notation:

$arr = ['foo', 'bar', 'baz'];
$arr = array_map( fn( $value ) => $value = '...' . $value, $arr );
// вывод: ['...foo', '...bar', '...baz']

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-08-12
@Shimpanze

Professionals, for example, understand that the $value assignment here is meaningless and do not write it. And so I saved you as many as 9 characters - spend them wisely.
Professionals also understand that readability is important in code, not brevity. And it is the ability to write understandable code that is an indicator of qualification.
Well, straight professional professionals solve this problem exclusively like this:

View professional code

<?php
declare(strict_types=1);

class Ellipsis
{
    private string $char;
    private int $count;

    /**
     * @param string $char
     * @param int $count
     */
    public function __construct(string $char, int $count)
    {
        $this->char = $char;
        $this->count = $count;
    }

    /**
     * @return string
     */
    public function getChar(): string
    {
        return $this->char;
    }

    /**
     * @return int
     */
    public function getCount(): int
    {
        return $this->count;
    }
}

class Ellipsisist
{
    private Ellipsis $ellipsis;

    /**
     * @param Ellipsis $ellipsis
     */
    public function __construct(Ellipsis $ellipsis)
    {
        $this->ellipsis = $ellipsis;
    }

    /**
     * @param string $value
     * @return string
     */
    public function __invoke(string $value): string
    {
        return str_pad($value, mb_strlen($value) + $this->ellipsis->getCount(), $this->ellipsis->getChar(), STR_PAD_LEFT);
    }
}

class EllipsisistFactory
{
    /**
     * @param string $char
     * @param int $count
     * @return Ellipsisist
     */
    public static function make(string $char, int $count): Ellipsisist
    {
        return new Ellipsisist(new Ellipsis($char, $count));
    }
}

$arr = ['foo', 'bar', 'baz'];

$ellipsisiatedArr = array_map(
    EllipsisistFactory::make('.', 3),
    $arr
);

var_dump($ellipsisiatedArr);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question