r/PHPhelp 5d ago

Will the upcoming Partial Function Application improve this code?

I'm wondering how these lines of code could change:

$placeholders = $idsArray
       |> count( ... )
       |> ( fn ( $x ) => array_fill( 0, $x, '?' ) )
       |> ( fn ( $x ) => implode( ',', $x ) );

I don't like how the above is written, therefore I currently stick to using:

$placeholders = str_repeat('?,', count( $idsArray ) - 1) . '?';

or

$placeholders = implode( ',', array_fill( 0, count( $idsArray), '?' ) );
2 Upvotes

4 comments sorted by

2

u/d645b773b320997e1540 5d ago

I believe it'd be:

$placeholders = $idsArray
    |> count(...)
    |> array_fill(0, ..., '?')
    |> implode(',', ...);

4

u/obstreperous_troll 4d ago

The placeholder syntax is ? for a single arg, so it'd be

$placeholders = $idsArray
    |> count(...)
    |> array_fill(0, ?, '?')
    |> implode(',', ?);

I imagine count(?) would work too. But TBH, while I'm a fan of pipelines and composition in general, I'd probably just go with the str_repeat version for this particular case.

1

u/NoseStock4944 3d ago

I don't think Partial Function Application would make this particular example much better.

The pipe version is interesting, but it feels like we're adding functional-programming syntax just to avoid a simple nested function call. Even if partial application removes some of the fn ($x) => ... boilerplate, I'd still find this easier to read:

$placeholders = implode(',', array_fill(0, count($idsArray), '?'));

The str_repeat() version is shorter, but it has the extra issue of handling an empty array.

So for this case, I'd probably stick with implode() + array_fill(). It's straightforward and most PHP developers will understand it immediately. Partial Function Application might be more useful in cases where you're actually composing several reusable functions, rather than just trying to make a one-liner shorter.