Strings in PHP

The string is commonly described as a collection of characters. Mean a string can be a collection of numbers, alphabets, or special symbols for example “Hello World”. In PHP you can define a string in the program in two ways by using single quotes(‘ ‘) or by using double(” “) quotes. Here we learn about strings, basic functions in strings, escape-sequence, and the difference between single and double-quote strings.

Difference between Single and Double Quote Strings: –

We can write strings in PHP in both single and double quotes. But there is a certain difference between both. If you write a string in single quotes it will take string literally. Suppose you have a variable $num=10; and if you write something like this ‘Value of num=$num’. In this case, it will show the same. But if you will write this in double quotes the variable name will be changed with its value. To understand it more clearly follow the given example.

<?php 
$num =10;
echo 'value of num = $num';
echo "value of num = $num";
?>

Escape-Sequence in strings: –

These are some special escape sequences in PHP that we can use with strings. These escape sequences get replaced with special values. Check these escape sequences.

  • \n is replaced with the newline character.
  • \\ is replaced with a single backslash. (\)
  • \r is replaced with the carriage-return character.
  • \t is replaced with the tab.
  • \” is replaced with a single double-quote (“).
  • \$ is replaced with the dollar sign itself ($).

Basic string Functions: –

Here we will check some of the basic functions with would so helpful to you while working with strings. Here is like of some basic string functions in PHP.

  • strlen(): function to check the total number of characters in a string.
  • str_replace(): function to replace part or parts of a string with another string.
  • str_word_count(): function to check the total number of words in a string.
  • strrev(): function to reverse a string in PHP.
Spread the love
Scroll to Top
×