PHP Strings

Spread the love

PHP Strings

Definition: PHP Strings are defined as the sequence of characters with a certain length.

Example: “This is PHP Strings tutorial by codingkala.com”.

Creating string variable:

$str 1 = “This is strings in PHP tutorial”;
$str2 = “123456”; //Numbers present inside double quotes will become strings of numbers.
$str3 = ‘codingkala.com contains PHP and other programming tutorials, lets see them all’; // String in single quotes.

As shown in above examples we can define string variables using single and double quotes.

 

Concatenating strings

We can concatenate two strings using dot(.) operator. Smaller strings can be combined to make one big string.

Example:

$str1 = “This is string one and “;
$str2 = ” this is string two.”;
$str = $str1 . $str2 . ” Both gets combined.”;
echo $str;
Output: This is string one and this is string two. Both gets combined.

Using special characters inside a string.

If we try to print certain characters inside string then we have to escape them using a backslash, else special characters will get treated as normal characters.

Few escape characters using backslash:

  1. to print new line inside a string, use – n
  2. to use tab inside a string, use -t
  3. to use carriage return or enter use – r
  4. to print double quotes use – “
  5. to print backslash, use – \
  6. to print a dollar sign, use – $
    etc.

 

Using variables with strings:

Let’s say in a program we want to print the value present inside variable with the string, then we have to use a complete string inside single quotes. If we use double quotes then values inside variables will not get printed.

Example:

$name = “Ajay”;
$emp_no = 10;

1. $str1 = “$name is having emplyee number $emp_no”;    //Using double quotes.
echo $str1;

Output: Ajay is having emplyee number 10   //Variable values are gets printed.

2. $str2 = ‘$name is having emplyee number $emp_no’;     //Using single quotes.
echo $str2;

Output: $name is having emplyee number $emp_no // Variable values are not get printed.

There are different string functions available to manipulate the string and performing various operations using string.

We will see in details about different PHP string functions in separate tutorials.


Spread the love

Leave a Comment