Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jericopulvera's avatar

What is the better way to write string together with php code?

I have this code in my notifications and I find myself thinking on how to concatenate php code together with string. What is the simpler way to write this?

public function toArray($notifiable)
{
    if ($this->follow) {
        $message = '<a href="/'.$this->user->usn.'">'. $this->user->name. '</a> followed you';
    } else {
        $message = '<a href="/'.$this->user->usn.'">'. $this->user->name. '</a> unfollowed you';
    }
    return [
        'user'   => $this->user,
        'message' => $message,
    ];
}
0 likes
3 replies
newbie360's avatar
sprintf('<a href="/%s">%s</a> followed you', $this->user->usn, $this->user->name);
1 like
newbie360's avatar
Level 24

??

public function toArray($notifiable)
{
    $abcdefg = ($this->follow) ? "followed you" : "unfollowed you";
    $message = sprintf('<a href="/%s">%s</a> %s', $this->user->usn, $this->user->name, $abcdefg);

    return [
        'user'   => $this->user,
        'message' => $message,
    ];
}

Please or to participate in this conversation.