PHP Strings

Single vs double quotes

This distinction matters more in PHP than in most languages:

  • Double quotes parse variables and escape sequences.
  • Single quotes are literal — faster, and safer when the text contains $.
PHP
<?php
  $name = "Sita";

  echo "Hello $name\n";   // Hello Sita  (+ newline)
  echo 'Hello $name\n';   // Hello $name\n  (literal)

Use {} when the variable is followed by characters that could be read as part of the name:

PHP
<?php
  $item = "book";
  echo "I bought two {$item}s"; // I bought two books

Concatenation

PHP
<?php
  $first = "Sita";
  $last  = "Karki";

  $full = $first . " " . $last; // Sita Karki
  $full .= "!";                  // append

Common string functions

PHP
<?php
  $s = "  Hello Nepal  ";

  echo strlen($s);              // 17 — length including spaces
  echo trim($s);                // "Hello Nepal"
  echo strtoupper($s);          // "  HELLO NEPAL  "
  echo strtolower($s);          // "  hello nepal  "
  echo str_replace("Nepal", "World", $s);
  echo substr("Hello", 0, 3);   // "Hel"
  echo strpos("Hello", "ll");   // 2 — position, or false if not found
  echo ucfirst("hello");        // "Hello"
  echo ucwords("hello nepal");  // "Hello Nepal"
  echo str_repeat("ab", 3);     // "ababab"

Careful with strpos()

It returns 0 when the match is at the very start — and 0 is falsy. Always compare with !== false:

PHP
<?php
  if (strpos("Hello", "H") !== false) {
      echo "found"; // correct
  }

  // if (strpos("Hello", "H")) { }  ← BUG: 0 is falsy, misses position 0

Splitting and joining

PHP
<?php
  $csv = "ram,shyam,hari";
  $names = explode(",", $csv);      // ["ram", "shyam", "hari"]
  $back  = implode(" | ", $names);  // "ram | shyam | hari"

Formatting numbers into strings

PHP
<?php
  printf("Total: NPR %.2f\n", 1234.5);      // Total: NPR 1234.50
  $s = sprintf("%05d", 42);                  // "00042"
  echo number_format(1234567.891, 2);        // "1,234,567.89"