Strings in PHP



In this tutorial, we will learn about strings in PHP. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.


What is a String

A string in PHP is a sequence of characters. Strings in PHP can be created using single quotes, double quotes, or the heredoc and nowdoc syntaxes. Strings are used for storing and handling text data.


Creating Strings

Strings can be created in PHP using single or double quotes:

$str = "Hello, world!";

Strings can also be created using heredoc syntax:

$str2 = <<


Example 1: Initializing Strings

  1. Create a string variable and initialize it with a value.
  2. Print the string variable using echo.

PHP Program

<?php
$str = "Hello, world!";
echo $str;
?>

Output

Hello, world!


Example 2: Accessing Characters in a String

  1. Create a string variable and initialize it with a value.
  2. Access and print individual characters using array indexing.

PHP Program

<?php
$str = "Hello";
echo $str[0] . "\n"; // Accessing using array indexing
echo $str[1] . "\n";
?>

Output

H
e


Example 3: Modifying Strings

  1. Create a string variable and initialize it with a value.
  2. Strings in PHP are mutable, so you can modify individual characters directly using array indexing or append new characters.
  3. Print the modified string.

PHP Program

<?php
$str = "Hello";
$str[0] = 'J'; // Modifying individual character
$str .= " World!"; // Appending new characters
echo $str;
?>

Output

Jello World!


Example 4: String Concatenation

  1. Create two string variables and initialize them with values.
  2. Concatenate the strings using the . operator.
  3. Print the concatenated string.

PHP Program

<?php
$str1 = "Hello";
$str2 = " World!";
$str3 = $str1 . $str2; // Concatenating strings
echo $str3;
?>

Output

Hello World!


Example 5: Finding Substrings

  1. Create a string variable and initialize it with a value.
  2. Use the strpos function to find a substring.
  3. Print the position of the found substring.

PHP Program

<?php
$str = "Hello, world!";
$pos = strpos($str, "world"); // Finding substring
if ($pos !== false) {
    echo "Found 'world' at position: $pos\n";
} else {
    echo "Substring not found\n";
}
?>

Output

Found 'world' at position: 7


Example 6: String Length

  1. Create a string variable and initialize it with a value.
  2. Use the strlen function to get the length of the string.
  3. Print the length of the string.

PHP Program

<?php
$str = "Hello, world!";
echo "Length of the string: " . strlen($str);
?>

Output

Length of the string: 13