Lesson 10 — Data Structures

Strings and String Functions

PHP includes an extensive library of built-in string functions for searching, formatting, and transforming text, alongside two different quoting styles with different behaviour.

Single vs Double Quotes

Double-quoted strings support variable interpolation and escape sequences like \n; single-quoted strings treat almost everything literally, which is slightly faster when interpolation isn't needed.

PHP — Quote styles
$name = "Bongani";
echo "Hello, $name!\n";      // Hello, Bongani!
echo 'Hello, $name!\n';      // Hello, $name!\n (literal text)

Common String Functions

A handful of built-in functions cover the majority of everyday string manipulation needs.

  • strlen($str) — number of characters.
  • strtolower() / strtoupper() — case conversion.
  • str_replace($search, $replace, $str) — find and replace text.
  • substr($str, $start, $length) — extract a portion of a string.
  • trim($str) — remove whitespace from both ends.

Common Mistakes

  • Using single quotes when variable interpolation was actually intended, resulting in the literal variable name being printed.
  • Forgetting that string indices in PHP start at 0 when using functions like substr.
  • Not trimming user input before validating it, so accidental leading/trailing spaces cause valid input to be rejected.
  • Mixing up the argument order in str_replace, which is (search, replace, subject) — the reverse of what some other languages use.

Professional Tip

Use single quotes for plain literal strings with no variables, and reserve double quotes for strings that need interpolation or escape sequences. This small habit makes it immediately clear, at a glance, which strings are dynamic.

Your Turn

Write a script that accepts a full name in one variable, trims any extra whitespace, and prints it in uppercase alongside its total character length.

Mini Quiz

Which quote style allows variables to be interpolated directly inside a string in PHP?