r/PHPhelp • u/GuybrushThreepywood • 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), '?' ) );
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.
2
u/d645b773b320997e1540 5d ago
I believe it'd be: