1. 12
    Concatenating strings in PHP
    3m 8s

Concatenating strings in PHP

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 2 years ago

Joining two strings together is something you will do a lot in PHP. Learn a few different ways to concatenate strings together.

Instructor: [0:00] You can join together one or many strings in PHP and there are a few ways to do it. As we learned in this last lesson, we can convert two strings together using a period, also known as a concatenation operator.

[0:15] For the sake of this lesson and so we don't start getting confused, let's set this num posts back to 10, which is an integer. Let's also remove these calls to get type because we no longer need them.

[0:31] First, if we want to display text right alongside this integer here, the easiest way to do this is outside of the PHP tag. Let's go ahead and type posts after this num post is outputted. When we refresh this screen, we will see 10 posts.

[0:49] Sometimes you will want to be able to do this programmatically. Let's create a new variable that manages the display of this text of number of posts. We will name this new variable, num posts display.

[1:04] We will set it equal to the contents that are outputted within this H2 tag. Let's assign it the value of num posts concatenated with posts. Remember to add the space here so the number is separated from the text.

[1:22] Remember that using this concatenation operator of a period makes both of these sides strings. This num post is automatically converted to a string. We can then output the data within this short echo tag, num post display, and then remove our extra posts text.

[1:41] When we refresh the page, the same output will be shown. There is another way to join strings together and that's by using what's called a combined operator. If we ever wish to assign the value that we are setting here over multiple lines, this is when we will use this method.

[1:59] For example, rather than concatenating on this post text, let's just set this to num posts. Then we will break posts out to another line. We will do this again by calling num post display, but setting it equal to this post string.

[2:17] We'll actually overwrite our previously existing variable. Instead of using an equals sign, we will use a period equals sign. When we save and refresh the output is the same.

[2:31] This is more of a procedural programming approach though, which means it runs through multiple lines using a top-down approach. There's actually another way to write this code as well.

[2:42] Instead of using a period equals sign here, we can actually use a period and then remove the previous semicolon. This is essentially the same as wrapping it all on its own line.

[2:57] Using multiple lines can sometimes be useful depending on how you are working with the code. For now, we will just set this to a single line because it's easier to read.