views:

98

answers:

4

I've been programming in PHP for years, and I've always wondered if there is a way to 'pre-concatenate' a string. Example:

$path = '/lib/modules/something.php';
$server = $_SERVER['DOCUMENT_ROOT'];

I've been doing this for years in order to append a value to the beginning of a string:

$path = $server . $path;
// returns: /home/somesite.com/public_html/lib/modules/something.php

Is there a shorthand for this? Just curious.

A: 

try out the sprintf function as it has worked for me - information on it here http://docs.php.net/sprintf

PaulStack
This just makes it longer, unfortunately.
Delan Azabani
A: 

No, but you could write your own function:

function pc(&$a, &$b) {
    $a = $b . $a;
}
pc($path, $server);

The above call to pc will set $path to $server . $path.

Delan Azabani
This is just making the whole code less readable.
Gumbo
A function like this is just a suggestion for a shorthand, as there is no in-built syntax for this. If you don't like it, don't use it...?
Delan Azabani
@Delan: Actually you wrote a method of a class. Still I agree with Gumbo on this one.
AntonioCS
This is the only real shorthand answer, though. I'm not saying it's necessarily good or bad to use, but OP wanted a shorthand, and I wrote one.
Delan Azabani
Why the downvotes? This is really the only valid answer.
Delan Azabani
A: 

A not so serious answer (I know it is longer):

$path = strrev($path);
$path .= strrev($_SERVER['DOCUMENT_ROOT']);
$path = strrev($path);

There is no limit to creativity! ;)

Felix Kling
A: 

a shorthand for concatenation is interpolation

  $path = "{$_SERVER['DOCUMENT_ROOT']}/lib/modules/something.php";
stereofrog
But interpolation does only work with literal strings and variables.
Gumbo
@Gumbo, arrays and objects work just fine in stings
stereofrog
@stereofrog: I rather meant that a literal string declaration is needed to concatenate variables. And you can only use variables and no other value returning expressions like functions calls etc.
Gumbo