PHP variable interpolation vs concatenation [duplicate]

Asked
Active3 hr before
Viewed126 times

8 Answers

variable
90%

Whatever works best for you works... But if you want to go for speed use this:, How to cite works that is cited in the works ,The single quotes tell PHP that no interpretation is needed, and the comma tells PHP to just echo the string, no concatenation needed., Convert string of coordinates to WKT for import into QGIS

Whatever works best for you works... But if you want to go for speed use this:

echo 'Welcome ', $name, '!';
88%

What is the difference between the two following methods (performance, readability, etc.) and what do you prefer?,The single quotes tell PHP that no interpretation is needed, and the comma tells PHP to just echo the string, no concatenation needed.,Whatever works best for you works... But if you want to go for speed use this:

What is the difference between the two following methods (performance, readability, etc.) and what do you prefer?

echo "Welcome {$name}s!"

vs.

echo "Welcome ".$name.
"!";
load more v
72%

I am wondering, What is the proper way for inserting PHP variables into a string? This way:,Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.,PHP will interpret your code as if you were trying to use the $names variable -- which doesn't exist. - note that it will only work if you use "" not '' for your string., 1 - Unless you are doing hundreds of thousands of concatenations vs interpolations -- and it's probably not quite the case.

I am wondering, What is the proper way for inserting PHP variables into a string?

This way:

echo "Welcome ".$name.
"!"

Or this way:

echo "Welcome $name!"
load more v
65%

Use Template String to Interpolate Variables Directly Into the String in PHP,Use String Template to Concatenate a PHP Variable With a String Literal by Assigning the Value of the String to a Variable,Use the Dot (.) Operator to Concatenate a PHP Variable With a String,We will introduce a way to concatenate a PHP variable with a string with template strings.

Example Code:

# php 7. *
   <
   ? php
$txt = "salt";
echo "{$txt}y"; ?
>
load more v
75%

I've read lots of old posts discussing about it. Some people say string interpolation is faster, others say string concatenation is faster.Which one is faster in 2020 using PHP 7?,You gain a ton of maintainability and cleanliness using that instead of building strings using concatenation or interpolation,Thank you. So I should use string interpolation as it’s easier,Is this just a thought question or do you have code where string operations are a bottleneck? Sounds interesting!

Code, if you don't want to run it on Repl.it:

< ? php
define('REPS', 1000);

$interpolation_start = microtime(true);

for ($i = 0; $i < REPS; $i++) {
   echo "Iteration number {$i}\n";
}

$interpolation_time = microtime(true) - $interpolation_start;

$concatenation_start = microtime(true);

for ($i = 0; $i < REPS; $i++) {
   echo 'Iteration number '.$i.PHP_EOL;
}

$concatenation_time = microtime(true) - $concatenation_start;

$delta = $interpolation_time - $concatenation_time;

echo "\n------------------------------------\n";
echo "Interpolation: {$interpolation_time}\n";
echo "Concatenation: {$concatenation_time}\n";
echo "Delta:         {$delta}\n";
echo "------------------------------------";
load more v
40%

Some languages do not offer string interpolation, instead offering a standard function where one parameter is the printf format string, and other(s) provide the values for each placeholder. ,There are two main types of expand variable algorithms for variable interpolation:[3] ,In Sciter any function with name starting from $ is considered as interpolating function and so interpolation is customizable and context sensitive: ,Scala 2.10+'s string interpolation allows embedding variable references directly in processed string literals. Here is an example:

An SQL injection example:

query = "SELECT x, y, z FROM Table WHERE id='$id' "
$name = "Alice";
print "${name} said Hello World to the crowd of people.";
DATA(apples) = 4.
WRITE | I have {
   apples
}
apples | .
I have 4 apples
apples = 4
echo "I have $apples apples"
# or
echo "I have ${apples} apples"
I have 4 apples
apples = 4
print("I have $(apples) apples")
# or
print("I have {0} apples" % apples)
I have 4 apples
var apples = 4;
var bananas = 3;

Console.WriteLine($ "I have {apples} apples");
Console.WriteLine($ "I have {apples + bananas} fruits");
I have 4 apples
I have 7 fruits
apples = 4;
writeOutput("I have #apples# apples");
<cfset apples=4>
   <cfoutput>I have #apples# apples</cfoutput>

The output will be:

I have 4 apples
apples = 4
console.log "I have #{apples} apples"
I have 4 apples
int apples = 4, bananas = 3;
print('I have $apples apples.');
print('I have ${apples+bananas} fruit.');
I have 4 apples.
I have 7 fruit.
lang: = "Golang"
apples: = 3
fmt.Printf("I am a %s developer.\n", lang)
fmt.Printf("I have %d apples.\n", apples)
I am a Golang developer.
I have 3 apples.
def quality = "superhero"
final age = 52
def sentence = "A developer is a $quality, if he is ${age <= 42 ? "
young " : "
seasoned "}"
println sentence
A developer is a superhero
if he is seasoned
var apples = 4;
var bananas = 3;
trace('I have $apples apples.');
trace('I have ${apples+bananas} fruit.');
I have 4 apples.
I have 7 fruit.
int apples = 4;
int bananas = 3;
System.out.println(String.format("I have %s apples and %s bananas", apples, bananas));
System.out.println(String.format("I have %s fruit", apples + bananas));
Object[] testArgs = {
   Long.valueOf(3),
   "MyDisk"
};

MessageFormat form = new MessageFormat(
   "The disk \"{1}\" contains {0} file(s).");

System.out.println(form.format(testArgs));
const apples = 4;
const bananas = 3;
console.log(`I have ${apples} apples`);
console.log(`I have ${apples + bananas} fruit`);
I have 4 apples
I have 7 fruit
console.log(`This is the first line of text.
This is the second line of text.`);
This is the first line of text.
This is the second line of text.
apples = 4
bananas = 3
print("I have $apples apples and $bananas bananas, making $(apples + bananas) pieces of fruit in total.")
I have 4 apples and 3 bananas, making 7 pieces of fruit in total.
val quality = "superhero"
val apples = 4
val bananas = 3
val sentence = "A developer is a $quality. I have ${apples + bananas} fruit"
println(sentence)
A developer is a superhero.I have 7 fruit
def apples = 4;
def bananas = 3;
Console.WriteLine($ "I have $apples apples.");
Console.WriteLine($ "I have $(apples + bananas) fruit.");
def fruit = ["apple", "banana"];
Console.WriteLine($ < #I have..$(fruit;
   "\n"; f => f + "s") # > );
apples
bananas
quality = "superhero"
apples = 4
bananas = 3
sentence = "A developer is a $quality. I have ${apples + bananas} fruit"
echo(sentence)
A developer is a superhero.I have 7 fruit
import strutils, strformat
var apples = 4
var bananas = 3
echo "I have $1 apples".format(apples)
echo fmt "I have {apples} apples"
echo fmt "I have {apples + bananas} fruits"

# Multi - line
echo fmt ""
"
I have {
   apples
}
apples ""
"

# Debug the formatting
echo fmt "I have {apples=} apples"

# Custom openChar and closeChar characters
echo fmt("I have (apples) {apples}", '(', ')')

# Backslash inside the formatted string literal
echo fmt ""
"{ "
yep\ nope " }"
""
I have 4 apples
I have 4 apples
I have 7 fruits
I have
4 apples
I have apples = 4 apples
I have 4 {
   apples
}
yep
ope
let numberOfApples = "4"; in "I have ${numberOfApples} apples"
I have 4 apples
const Apples: = 4
const Bananas: = 3
Println("I have `(Apples) apples.\n")
Println("I have `(Apples+Bananas) fruit.\n")
I have 4 apples.
I have 7 fruit.
my $apples = 4;
my $bananas = 3;
print "I have $apples apples.\n";
print "I have @{[$apples+$bananas]} fruit.\n";
# Uses the Perl array(@) interpolation.
I have 4 apples.
I have 7 fruit.
< ? php
$apples = 5;
$bananas = 3;
echo "There are $apples apples and $bananas bananas.";
echo "\n";
echo "I have {$apples} apples and {$bananas} bananas.";
There are 5 apples and 3 bananas.
I have 5 apples and 3 bananas.
# in all versions
apples = 4
bananas = 3
print("I have %d apples and %d bananas" % (apples, bananas)) # no longer recommended
print("I have %(apples)d apples and %(bananas)d bananas" % locals()) # no longer recommended
# with Python 2.6 +
   print("I have {0} apples and {1} bananas".format(apples, bananas))
print("I have {a} apples and {b} bananas".format(b = bananas, a = apples))
# with Python 2.7 +
   print("I have {} apples and {} bananas".format(apples, bananas))
# or with Python 3.6 +
   print(f "I have {apples} apples and {bananas} bananas")
I have 4 apples and 3 bananas
apples = 4
puts "I have #{apples} apples"
# or
puts "I have %s apples" % apples
# or
puts "I have %{a} apples" % {
   a: apples
}
I have 4 apples
let (apples, bananas) = (4, 3);
println!("There are {} apples and {} bananas.", apples, bananas);

The output will be:

There are 4 apples and 3 bananas.
val apples = 4
val bananas = 3
//before Scala 2.10
printf("I have %d apples\n", apples)
println("I have %d apples"
   format apples)
//Scala 2.10+
println(s "I have $apples apples")
println(s "I have ${apples + bananas} fruits")
println(f "I have $apples%d apples")
I have 4 apples
var apples = 4
var bananas = 3
var domElement = ...;

domElement.$content(<p>I have {apples} apples</p>);
domElement.$append(<p>I have {apples + bananas} fruits</p>);
domElement.$content(<p>I have {apples} apples</p>);
domElement.html = "<p>I have " + apples.toHtmlString() + " apples</p>";
   apples = 4;
   bananas = 3
   Output = "I have "
   apples " apples."
   Output = "I have "(apples + bananas)
   " fruit."
I have 4 apples.
I have 7 fruit.
let apples = 4
print("I have \(apples) apples")
I have 4 apples
set apples 4
puts "I have $apples apples."
I have 4 apples.
set apples 4
puts[format "I have %d apples."
   $apples]
var apples: number = 4;
console.log(`I have ${apples} apples`);
I have 4 apples
var apples: number = 4;
console.log("I have %d apples", apples);
name = "Tom"
Console.WriteLine($ "Hello, {name}")
load more v
22%

Concatenate (perform memory copy) to this latter buffer “I like ” and “foo”, return a temp buffer;,Concatenate (perform a memory copy) “I like foo and ” and “bar”, to this latter buffer and return it;,Concatenate (perform memory copy) “I like foo ” and “and “, to this latter buffer and return a temp buffer;,We create 1.000 encapsed strings, in which we can find some piece of static strings and 6 string based variables, two of which weighting at 1Kb.

Encapsed strings are strings where in-variable scan occur. Those are strings declared using double-quotes or the Heredoc syntax. The algorithm needs to analyze the string, and separate each string part from the variable part. Consider this example :

$a = 'foo';
$b = 'bar';

$c = "I like $a and $b";
load more v
60%

If an interpolated string has the type IFormattable or FormattableString, the compiler generates a call to the FormattableStringFactory.Create method.,Conversion of an interpolated string to an IFormattable instance that also allows you to create multiple result strings with culture-specific content from a single IFormattable instance.,Conversion of an interpolated string to an IFormattable instance that also allows you to create multiple result strings with culture-specific content from a single IFormattable instance. ,For more information, see the Interpolated strings section of the C# language specification.

String interpolation provides a more readable, convenient syntax to format strings. It's easier to read than string composite formatting. Compare the following example that uses both features to produce the same output:

string name = "Mark";
var date = DateTime.Now;

// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// String interpolation:
Console.WriteLine($ "Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// Both calls produce the same output that is similar to:
// Hello, Mark! Today is Wednesday, it's 19:40 now.
load more v

Other "variable-undefined" queries related to "PHP variable interpolation vs concatenation [duplicate]"