Any equivalent to .= for adding to beginning of string?

04/17/2020 02:30:01

Just wondering if there is something like .= for adding text to the beginning of a string, e.g.:

$foo =. 'bar';

which doesn't work.

Edit: example was originally $foo =. $bar; which can be achieved with $bar .= $foo;

Verified Answer (155 Votes)

08/18/2011 22:52:13

Nope. But you can do

$foo = "bar" . $foo

Answer #2 (4 Votes)

08/18/2011 23:03:31

You could always make your own function for that:

function prepend($string, $chunk) {
     if(!empty($chunk) && isset($chunk)) {
        return $string.$chunk;
     else {
        return $string;

$string would be the piece that you want to prepend and $chunk would be the text that you want something prepended onto it.

You could say the checks are optional, but by having that in there you don't need to worry about passing in a null value by accident.


Answer #3 (3 Votes)

02/25/2015 20:07:09

I know this was asked/answered a while ago, but providing this answer as it is functionally equivalent despite it not being an assignment operator and no one commented on its usage for general string concatenation.

You may want to look into the use of the sprintf (documentation) family of functions for string concatenation. It provides a lot more sanitization and usability than just combining two strings with assignment operators.

$foo = 'foo';

$append = sprintf('%1$s%2$s', $foo, 'bar');
/* string(6) "foobar" */

$prepend = sprintf('%1$s%2$s', 'bar', $foo);
/* string(6) "barfoo" */

$prependInvert = sprintf('%2$s%1$s', $foo, 'bar');
/* string(6) "barfoo" */

$wrap = sprintf('%2$s%1$s%2$s', $foo, 'bar');
/* string(6) "barfoobar" */

I normally use vsprintf, since working with arrays is easier to manage value positions than individual arguments.

$vprepend = vsprintf('%2$s%1$s', array('foo', 'bar'));
/* string(6) "barfoo" */

Also with an array of values, one can simply implode the resultant set of values for simple string concatenation.

 var_dump(implode('', array('bar', 'foo')));
 /* string(6) "barfoo" */
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.