What do you mean by string in php?

What is String in PHP?

A string is a collection of characters. String is one of the data types supported by PHP.

The string variables can contain alphanumeric characters. Strings are created when;

  • You declare variable and assign string characters to it
  • You can directly use PHP Strings with echo statement.
  • PHP String functions are language construct, it helps capture words.
  • Learning how strings work in PHP and how to manipulate them will make you a very effective and productive developer.

In this PHP Tutorial, you will learn-

  • What is String in PHP?
  • PHP Create Strings Using Single quotes with Example
  • PHP Create Strings Using Double quotes with Example
  • PHP Heredoc with Example
  • PHP Nowdoc with Example
  • PHP String Function Examples

PHP Create Strings Using Single quotes with Example

Let’s now look at the four different ways of creating PHP string functions and string manipulation in PHP.

Creating PHP Strings Using Single quotes: The simplest way to create a string is to use single quotes.

Let’s look at an example that creates a simple string in PHP.

Output:

string[42] "You need to be logged in to view this page"

If the single quote is part of the string value, it can be escaped using the backslash.

The code below illustrates how to escape a single quote.

Output:

I'll be back after 20 minutes

PHP Create Strings Using Double quotes with Example

The double quotes are used to create relatively complex strings compared to single quotes.

Variable names can be used inside double quotes and their values will be displayed.

Let’s look at an example.

HERE,

  • The above example creates a simple string with the value of Alicia.
  • The variable name is then used in the string created using double quotes and its value is interpolated at run time.

Output:

Alicia is friends with kalinda

In addition to variable interpolations, the double quote string can also escape more special characters such as “\n for a linefeed, \$ dollar for the dollar sign” etc.

More examples Let’s suppose that we have the following code

Output:

NOTICE : Undefined variable
pas

executing the above codes issues a notice “Notice: Undefined variable”.

This is because $word is treated as a variable.

If we want the dollar sign to be treated as a literal value, we have to escape it.

Output:

pas$word

PHP Heredoc with Example

This heredoc methodology is used to create fairly complex strings as compared to double quotes.

The heredoc supports all the features of double quotes and allows creating string values with more than one line without PHP string concatenation.

Using double quotes to create strings that have multiple lines generates an error.

You can also use double quotes inside without escaping them.

The example below illustrates how the Heredoc method is used to create string values.

HERE,

Chủ Đề