php string add to string

What is the best way to add two strings together?

I read somewehere (I thought on codinghorror) that it is bad practice to add strings together as if they are numbers, since like numbers, strings cannot be changed. Thus, adding them together creates a new string. So, I was wondering, what is the best way to add two strings together, when focusing on performance?

Which of these four is better, or is there another way which is better?

Does it even matter?

12 Answers 12

String Concatenation with a dot is definitely the fastest one of the three methods. You will always create a new string, whether you like it or not. Most likely the fastest way would be:

If you are going to use this just for output with echo, then use the feature of echo that you can pass it multiple parameters, as this will not generate a new string:

For more information on how PHP treats interpolated strings and string concatenation check out Sarah Goleman’s blog.

You are always going to create a new string whe concatenating two or more strings together. This is not necessarily ‘bad’, but it can have performance implications in certain scenarios (like thousands/millions of concatenations in a tight loop). I am not a PHP guy, so I can’t give you any advice on the semantics of the different ways of concatenating strings, but for a single string concatenation (or just a few), just make it readable. You are not going to see a performance hit from a low number of them.

Here’s the quick and dirty test code, to understand the performance bottlenecks.

Single concat:

I get these results:

Many concats (10):

10% time difference on a microbenchmark like this is actually negligible. I’d say that since you proven «$str» to be the fastest way with growing amount of concats (with a visible 50% time difference), you should rather say that «$str» is usually the preferred way to concat strings.

Unless its really large amount of text it really doesnt matter.

and for large number of strings, you can put them in an array, and use implode() to get a string out of them.

Oh, and «adding strings» sounds bad, or at least ambiguous. In most languages, we prefer to speak of string concatenation.

It doesn’t matter unless used in a looong loop. In usual cases focus on code readability, even if you lost several processor cycles.

Example 1 and 2 are similar, I don’t think there should be much difference, this would be the fastes of all. No. 1 might be slightly faster.

Example 3 will be slower, as sprintf format (‘%s %s’) needs to be parsed.

But firstly, is concatenating strings a performance problem? It’s very unlikely, you should profile code to measure how much time does it take to run it. Then, replace the concatenating method with a different one and time again.

If you identify it as a problem, try googling for php string builder class (there are some to be found) or write your own.

Found this post from Google, and thought I’d run some benchmarks, as I was curious what the result would be. (Benchmarked over 10,000 iterations using a benchmarker that subtracts its own overhead.)

So there’s not much in it. Probably good to avoid sprintf() and implode() if you need something to be screaming fast, but there’s not much difference between all the usual methods.

there are 3 types of string joining operations.

Concatenate, take 2 string, allocate memory size length1+length2 and copy each into the new memory. quickest for 2 strings. However, concatenating 10 strings then requires 9 concat operations. The memory used is the 1st string 10 times, 2nd string 10 times, 3rd string 9 times, 4th string 8 times, etc. Runs X+1 +(X-1)*2 operations using more memory each cycle.

sprintf (array_merge, join, etc), take all the strings together, sum their length, allocate a new string of size sum, then copy each string into its respective place. memory used is 2*length of all initial strings, and operations is 2*X (each length, each copy)

ob (output buffer) allocate a generic 4k chunk and copies each string to it. memory 4k + each initial string, operations = 2 + X. (start, end, each copy)

Pick your poison. OB is like using a memory atom bomb to join 2 small strings, but is very effective when there are many joins, loops, conditions or the additions are too dynamic for a clean sprintf. concat is the most efficient to join a few fixed strings, sprintf which works better for building a string out of fixed values at one time.

Источник

Adding a String Within a String in PHP

I have a basic string question in PHP.

How would I go about adding a string after ‘titled’ and before ‘and’? If I had the title in a another variable, let say

What function or method could I use to do this?

5 Answers 5

There are a few options.

If you are using php with html and want to print the string (outside of php tags)

You just need to use double quotes and put the variable inside the string, like so:

php string add to string. Смотреть фото php string add to string. Смотреть картинку php string add to string. Картинка про php string add to string. Фото php string add to string

I’d recommend using a placeholder in your original string, and then replacing the placeholder with your title.

So, amend your code to be like this:

Then, you can use str_replace to replace your placeholder with the actual title, like this:

The easy way would be:

If you’re asking how to find where to insert, you could do something like this:

The third was is to place a token that’s unlikely to appear in the text like ||TITLE||. Search for that and replace it with the title text like:

Take advantage of your friend string interpolation (as GreenWevDev said).

Or if you need to replace the word title with a string, and only on its own, you can with regex.

php string add to string. Смотреть фото php string add to string. Смотреть картинку php string add to string. Картинка про php string add to string. Фото php string add to string

Not the answer you’re looking for? Browse other questions tagged php string add or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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

This way:

Or this way:

14 Answers 14

Between those two syntaxes, you should really choose the one you prefer 🙂

Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.

As a sidenote, so my answer is a bit more complete: the day you’ll want to do something like this:

That day, you’ll need to use <> :

No need to fallback to concatenations.

Also note that your first syntax:

Could probably be optimized, avoiding concatenations, using:

(But, as I said earlier, this doesn’t matter much. )

Double-quoted strings are more elegant because you don’t have to break up your string every time you need to insert a variable (like you must do with single-quoted strings).

However, if you need to insert the return value of a function, this cannot be inserted into a double-quoted string—even if you surround it with braces!

Since php4 you can use a string formater:

From the point of view of making thinks simple, readable, consistent and easy to understand (since performance doesn’t matter here):

Using embedded vars in double quotes can lead to complex and confusing situations when you want to embed object properties, multidimentional arrays etc. That is, generally when reading embedded vars, you cannot be instantly 100% sure of the final behavior of what you are reading.

AFAIK, you cannot embed constants.

In some specific cases, «double quotes with vars embedding» can be useful, but generally speaking, I would go for concatenation (using single or double quotes when convenient)

php string add to string. Смотреть фото php string add to string. Смотреть картинку php string add to string. Картинка про php string add to string. Фото php string add to string

I know this question already has a chosen answer, but I found this article that evidently shows that string interpolation works faster than concatenation. It might be helpful for those who are still in doubt.

Either one is fine. Use the one that has better visibility for you. And speaking of visibility you can also check out printf.

I prefer this all the time and found it much easier.

php string add to string. Смотреть фото php string add to string. Смотреть картинку php string add to string. Картинка про php string add to string. Фото php string add to string

Do not concatenate. It’s not needed, us commas as echo can take multiple parameters

Regarding using single or double quotes the difference is negligible, you can do tests with large numbers of strings to test for yourself.

Go with the first and use single quotes!

You should also check PHP variable concatenation, phpbench.com for some benchmarks on different methods of doing things.

It only matter of taste.
Use whatever you wish.

Most of time I am using second one but it depends.

Let me suggest you also to get yourself a good editor which will highlight a variable inside of a string

php string add to string. Смотреть фото php string add to string. Смотреть картинку php string add to string. Картинка про php string add to string. Фото php string add to string

You Should choose the first one. They have no difference except the performance the first one will be the fast in the comparison of second one.

If the variable inside the double quote PHP take time to parse variable.

I did not understand why this answer in above link get upvoted and why this answer got downvote.

As I said same thing.

You can look at here as well

I know this is an old question, but I think someone has to mention all pros & cons:

Better Syntax: That’s personal preference.

Performance: No difference. As many mentioned, double-quote might be faster if using unrealistically many variables.

Readability: No difference (may personal preference apply).

Writability/Re-Writability/Debugging: In 1-line statements there is no difference, but when dealing with multiple lines, it’s easier to comment/uncomment lines while debugging or writing. For example:

Less Changes: Single quote. For example if you have the following code:

But for double quote, you will need to change this:

Conclusion: Use what you prefer.

Источник

PHP Strings

A string is a sequence of characters, like «Hello world!».

PHP String Functions

In this chapter we will look at some commonly used functions to manipulate strings.

The PHP strlen() function returns the length of a string.

Example

Return the length of the string «Hello world!»:

The PHP str_word_count() function counts the number of words in a string.

Example

Count the number of word in the string «Hello world!»:

The PHP strrev() function reverses a string.

Example

Reverse the string «Hello world!»:

The PHP strpos() function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.

Example

Search for the text «world» in the string «Hello world!»:

Tip: The first character position in a string is 0 (not 1).

The PHP str_replace() function replaces some characters with some other characters in a string.

Example

Replace the text «world» with «Dolly»:

Complete PHP String Reference

For a complete reference of all string functions, go to our complete PHP String Reference.

The PHP string reference contains description and example of use, for each function!

PHP Exercises

We just launched
W3Schools videos

COLOR PICKER

php string add to string. Смотреть фото php string add to string. Смотреть картинку php string add to string. Картинка про php string add to string. Фото php string add to string

LIKE US

Get certified
by completing
a course today!

CODE GAME

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials

Top References

Top Examples

Web Courses

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *