Originally published on zero2php.dev — part of the Zero to PHP course. View this lesson on the original site.

Where to look things up

PHP has many string helpers—bookmark String functions. Early hits:

  • strlen($s) — length in bytes (UTF-8 nuance comes later)
  • substr($s, $start, $length) — slice
  • str_contains($haystack, $needle) — PHP 8+ boolean search
  • trim($s) — remove outer whitespace

Example

<?php

declare(strict_types=1);

$s = '  hello  ';
echo strlen($s), "\n";
echo '[' . trim($s) . "]\n";

Reading the manual

Read function pages for argument order—it matters.

Exercise

For $s = ' tree ', echo the length of trim($s) (digits only—the word has 4 letters).

From Zero to PHP — PHP foundations: environment, syntax, and values