7

I'm new to PHP, so please excuse the question.

I was wondering if PHP had a string format function such as Python's f-strings function, not str.format(). I have seen a few posts regarding the subject, but most of the examples accepted as answers refer to Python's older way of dealing with formatted strings str.format(). In my case I would like to build a variable using a formatted string for example (Python):

f_name = "John"
l_name = "Smith"
sample = f`{f_name}'s last name is {l_name}.`
print(sample)

I know I can use (PHP):

 $num = 5;
 $location = 'tree';
 $format = 'There are %d monkeys in the %s';
 echo sprintf($format, $num, $location);

but what if I want to use $format as a variable? The main idea is to create a dynamic variable based on other variables for instance:

$db_type = $settings['db_type'];  # mysql
$db_host = $settings['db_host'];  # localhost
$db_name = $settings['db_name'];  # sample

var $format = "%s:host=%s; dbname=%s";

# Not sure what to do after that, but I can use string concatenation:

var $format = $db_type + ":host=" + $db_host + "; dbname=" + $db_name;
var $connection = new PDO($format, $db_user, $db_password);

NOTE: I'm aware that there are several ways to do string concatenation per the PHP documentation, however I was not really able to find anything like this.

artomason
  • 3,625
  • 5
  • 20
  • 43
  • Instead of echoing the sprintf result, just assign it to a variable. – Patrick Q Feb 25 '19 at 22:23
  • 6
    Yes, use PHP template: `$f_name = "John"; $l_name = "Smith"; $sample = "{$f_name}'s last name is {$l_name}."` –  Feb 25 '19 at 22:24

1 Answers1

13

You can append any variable to any other variable with string concatenation using the dot notation:

$num = 5;
$location = 'tree';
$output = 'There are ' . $num . ' monkeys in the ' . $location; // There are 5 monkeys in the tree

Or the .= notation:

$a = "Hello ";
$b = "World";
$a .= $b; // $a now contains "Hello World"

You can also make use of a single string contained within double-quotes, which automatically evaluates the variable(s). Note that single-quotes do not evaluate variables:

$num = 5;
$location = 'tree';
echo 'There are $num monkeys in the $location'; // There are $num monkeys in the $location
echo "There are $num monkeys in the $location"; // There are 5 monkeys in the tree

And this works the same when assigning to variables:

$num = 5;
$location = 'tree';
$output = "There are $num monkeys in the $location"; // There are 5 monkeys in the tree

This can be further clarified with curly brackets:

$output = "There are {$num} monkeys in the {$location}"; // There are 5 monkeys in the tree
// OR
$output = "There are ${num} monkeys in the ${location}"; // There are 5 monkeys in the tree
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71