PHP 8.5 adds |>

The |> operator appears in many languages, mostly in the functional world. F# has essentially the exact same operator, as does OCaml. Elixir has a slightly fancier version (which we considered but ultimately decided against for now)

6 Likes

What is fancier about the Elixir one than the F#/OCaml one?

2 Likes

If I’m reading that page correctly, the right-hand side only allows for functions expecting a single argument whereas in Elixir the left-hand side becomes the value of the first argument on the right-hand side. My understanding comes from this line in the page linked:

The pipe operator, spelled |> , is deceptively simple. It takes the value on its left side and passes it as the single argument to a function (or in PHP’s case, callable ) on its right side

All of their examples seem to support this:

$string = 'something GoesHERE';

$newString = match ($format) {
    'snake_case' => $string
        |> splitString(...)
        |> fn($x) => implode('_', $x)
        |> strtolower(...),
    'lowerCamel' => $string
        |> splitString(...),
        |> fn($x) => array_map(ucfirst(...), $x)
        |> fn($x) => implode('', $x)
        |> lcfirst(...),
    // Other case options here.
};

There’s some syntax in that example I’m not familiar with (last time I did any serious PHP was in 2007), but my guess is that would be the difference.

2 Likes

Ocaml and F# have currying, so they don’t need to support more than 1-arity. Elixir has established a convention of treating the first argument as the “subject”, so piping into the first argument makes sense. In PHP’s case, there is neither currying, nor established convention for argument order. I think piping will be not be as elegant here.

5 Likes

Maybe they need something like we have in Arrows — arrows v0.2.1

# Standard first position pipe
2 |> Integer.to_string()
"2"

# Using ellipsis to place the piped value in a non-first position
3 |> String.pad_leading("2", ..., "0")
"002"
1 Like

While on the topic of PHP there was a nice article about it just yesterday on Devtalk..

As much as I was never a fan of the syntax, it’s hard to deny that PHP sites can run well without issue for a decent period - I still manage some forums (running on PHP) that haven’t been updated in 15 years!

1 Like

I still use it for small server-side interactions (though not for anything that has survived). It’s still the obvious choice for that that kind of thing, but lordy can I never get used to $.

2 Likes

It’d be nice if Elixir core had all the arrows functionality baked in :slightly_smiling_face:

This is a dead horse that has been thoroughly beaten several times over. It’s never going to happen, but there are several options if you really want it.

3 Likes