Any equivalent. = To append to the beginning of a line in PHP?

Just wondering if there is something like: = to add text to the beginning of the line, for example:

$foo =. 'bar'; 

which does not work.

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

+62
php
Aug 18 '11 at 17:50
source share
5 answers

Nope. But you can do

 $foo = "bar" . $foo 
+93
Aug 18 '11 at 17:52
source share

You can always make your own function for this:

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

$string will be the part you want to add, and $chunk will be the text you want to add to it.

You can say that checks are optional, but if you need it, you don’t have to worry about accidentally passing a null value.

+3
Aug 18 '11 at 18:03
source share

I know this was asked / answered some time ago, but provided this answer as it is functionally equivalent, despite the fact that it is not an assignment operator, and no one has commented on its use for general string concatenation.

You might want to check out the sprintf ( documentation ) family of functions for concatenating strings. This provides much more sanitation and usability than just combining two lines with assignment operators.

 $foo = 'foo'; $append = sprintf('%1$s%2$s', $foo, 'bar'); var_dump($append); /* string(6) "foobar" */ $prepend = sprintf('%1$s%2$s', 'bar', $foo); var_dump($prepend); /* string(6) "barfoo" */ $prependInvert = sprintf('%2$s%1$s', $foo, 'bar'); var_dump($prependInvert); /* string(6) "barfoo" */ $wrap = sprintf('%2$s%1$s%2$s', $foo, 'bar'); var_dump($wrap); /* string(6) "barfoobar" */ 

I usually use vsprintf , since working with arrays is easier to control the positions of values ​​than separate arguments.

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

Also with an array of values, just implode resulting set of values ​​for simple string concatenation.

  var_dump(implode('', array('bar', 'foo'))); /* string(6) "barfoo" */ 
+2
Feb 25 '15 at 15:07
source share

You can wrap the built-in substr_replace function, where the arguments $ start and $ length can be set to 0, which adds $ substitution to the string $ string and returns the result:

 function prepend(& $string, $prefix) { $string = substr_replace($string, $prefix, 0, 0); } 

An example of using an auxiliary function:

 $email_message = "Jonathan"; $appropriate_greeting = "Dear "; prepend($email_message, $appropriate_greeting); echo $email_message; 

If you do procedural programming, that is.

+1
Dec 6 '15 at 18:58
source share
  $foo = "Some Foo Text"; $bar = "Some Bar Text"; echo $foo.$bar // Some Foo TextSome Bar Text echo $bar.$foo // Some Bar TextSome Foo Text $foobar = $foo.$bar $boofar = $bar.$foo 
0
Aug 18 2018-11-18T00:
source share



All Articles