🧡 Strings β€” PHP

Home: Interview Prep Index

PHP strings are immutable sequences of bytes. Most string operations return new strings. Strings can be treated like arrays for character access ($s[0]), but modification creates a new value.


Subtopics

#TopicDescription
01String BasicsCreation, access, slicing, ASCII, common ops
02PHP String Functionsstrpos, str_replace, explode, preg_match and more
03PatternsTwo pointers, sliding window, palindromes, KMP
04Top 25 Interview QuestionsSolved problems with approach sections

The Big Picture

STRINGS IN PHP
β”‚
β”œβ”€β”€ Basics                ← length, access, slice, ASCII
β”‚   β”œβ”€β”€ strlen($s)
β”‚   β”œβ”€β”€ $s[0], $s[$i]
β”‚   β”œβ”€β”€ substr($s, start, len)
β”‚   └── ord($c), chr($n)
β”‚
β”œβ”€β”€ Built-in Functions    ← PHP standard library
β”‚   β”œβ”€β”€ strpos / strrpos
β”‚   β”œβ”€β”€ str_replace / str_repeat
β”‚   β”œβ”€β”€ explode / implode
β”‚   β”œβ”€β”€ strtolower / strtoupper / ucfirst
β”‚   β”œβ”€β”€ trim / ltrim / rtrim
β”‚   β”œβ”€β”€ str_split / str_contains
β”‚   └── preg_match / preg_replace
β”‚
β”œβ”€β”€ Patterns              ← DSA on strings
β”‚   β”œβ”€β”€ Two Pointers      ← reverse, palindrome, two-sum
β”‚   β”œβ”€β”€ Sliding Window    ← longest no-repeat, min window
β”‚   β”œβ”€β”€ Hashing           ← anagram, frequency count
β”‚   └── Recursion         ← palindrome partitioning
β”‚
└── Interview Questions   ← Top 25 problems

Complexity Cheat Sheet

OperationTimeNotes
Length strlen($s)O(n)PHP recalculates each time
Access $s[$i]O(1)Array-like access
Concatenation .O(n)Creates new string
Search strposO(nΓ—m)Naive search
Reverse strrevO(n)Built-in
Substring substrO(k)k = length of result
Split explode / str_splitO(n)
Replace str_replaceO(nΓ—m)

PHP vs JS String Syntax Comparison

OperationPHPJavaScript
Lengthstrlen($s)s.length
Access char$s[$i]s[i]
Substringsubstr($s, 1, 3)s.slice(1, 4)
Findstrpos($s, 'x')s.indexOf('x')
Reversestrrev($s)s.split('').reverse().join('')
Splitstr_split($s)s.split('')
Joinimplode('', $arr)arr.join('')
Upperstrtoupper($s)s.toUpperCase()
ASCIIord($c)s.charCodeAt(i)
Char from intchr($n)String.fromCharCode(n)