Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Can you update a var inside a string?

Tags:

variables

php

If you have

$a = 'World'

$str = 'Hello '.$a

$a = ' John Doe'

Is there a way in PHP that $str would now receive the changed value from $a? What I know I get: $str = 'Hello World', what I would like: $str = 'Hello John Doe'

I know this could be done by replacing the old value with str_replace, but I would like to ask if there is a way that this var could be passed by reference or something.

like image 915
CMA Avatar asked Jan 29 '23 13:01

CMA


1 Answers

In short once you've set a string, its set. It doesn't get bound with arguments on anything like that.

People tend to use formatted strings for things like this:

 $formattedString = "Hello %s".PHP_EOL;
 $possibleValues = [ "World", "John Doe" ];

 foreach ($possibleValues as $value) {
      printf($formattedString, $value);
 }

Prints:

Hello World

Hello John Doe

See it run at : http://sandbox.onlinephpfunctions.com/code/a9e8e7c71058b1e9a9212fbb398f9c40d20881b5

like image 85
apokryfos Avatar answered Feb 02 '23 10:02

apokryfos