Add Character to String in PHP

Strings are a sequence of characters considered immutable (unchanging once created). But how do we add characters to strings in PHP?

This post will explain how to add characters to a string in PHP.

PHP provides different built-in methods and approaches to add a character to a string. Importantly, the string will not be changed but rather a copy of the string with the new character created due to its immutable property.

Add Character to Start of String in Php

To add a character to the beginning of the string, use the concatenation (.) operator. Unlike Java, where you can specify a datatype to be a character, all characters are strings, and so the . operator works to add them together.

In the code, all we do is place the character before the . operator and the string we want to add the character.

Output

Add Character to End of String in Php

As in the previous section, we can use the concatenation (.) operator to add a character to the end of a string. Here, we place the string to which we want to add the character before the . operator and the character.

Output

Add Character to String at A Given Position

Using substr_Replace Method

PHP provides a built-in method called substr_replace, which replaces text within a portion of a string. The method creates a copy of the string with the replaced text, but to add a character; we need to specify certain parameters.

To use the function, we need to specify the following parameters;

  • $str: The string we want to add the character to
  • $char: The character we want to add
  • $offset: The offset determines where the replacing begins, and
  • The length represents the length of the portion of the string that will be replaced.

For the length parameter, the value will be zero since we are not replacing anything but placing a character after the offset position.

In the code, we specify the $char replace text to the $str starting at index 2 where the length of the text is 0.

Output

Using substr Method

We can use another PHP built-in method called substr. The substr method returns a portion of the string based on the offset and length parameters, as mentioned in the substr_replace method.

This approach splits the string into two: the first half is the string characters before the offset position, and the second is the string characters after the offset position. Then places the character between the two halves and concatenates them.

Output

That’s all about how to add character to String in PHP

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *