Beginner Fundamentals

PHP Strings

A string is a sequence of characters, such as a word or a sentence. PHP offers flexible ways to create and work with strings.

Single vs double quotes

Single quotes treat text literally. Double quotes parse variables and escape sequences.

<?php
$name = "Mia";
echo 'Hello, $name';  // Hello, $name
echo "Hello, $name";  // Hello, Mia
echo "Line\nbreak";   // \n becomes a new line

Concatenation

Join strings with the dot operator.

<?php
$greeting = "Good" . " " . "morning";
echo $greeting; // Good morning

Common string functions

PHP includes many helpers for working with text.

<?php
$text = "Hello World";

echo strlen($text);              // 11 (length)
echo strtoupper($text);          // HELLO WORLD
echo strtolower($text);          // hello world
echo str_replace("World", "PHP", $text); // Hello PHP

Quick reference

  • strlen() counts characters
  • strtoupper() / strtolower() change case
  • str_replace() replaces text
  • trim() removes spaces from the ends
<?php
echo trim("  spaced  "); // "spaced"