🧡 String Basics β€” PHP

Parent: Strings PHP Index


1. Creating Strings

$s1 = 'hello';           // single quotes β€” no interpolation
$s2 = "hello";           // double quotes β€” allows interpolation
$name = 'World';
$s3 = "Hello, $name!";   // "Hello, World!"
$s4 = 'Hello, ' . $name . '!'; // concatenation

// Heredoc
$long = <<<EOT
Line one
Line two
EOT;

2. String Length

$s = "hello";
echo strlen($s); // 5

// ⚠️ strlen counts BYTES, not characters
$utf = "hΓ©llo";
echo strlen($utf);   // 6 (UTF-8 bytes)
echo mb_strlen($utf); // 5 (characters)

3. Accessing Characters

$s = "hello";
echo $s[0];       // 'h'
echo $s[1];       // 'e'
echo $s[-1];      // 'o' (PHP 7.1+)

// Loop over characters
for ($i = 0; $i < strlen($s); $i++) {
    echo $s[$i]; // h e l l o
}

// str_split to array
$chars = str_split($s);  // ['h','e','l','l','o']
foreach ($chars as $c) echo $c;

4. Substrings

$s = "Hello World";

substr($s, 0, 5);   // "Hello"   β€” start 0, length 5
substr($s, 6);      // "World"   β€” from index 6 to end
substr($s, -5);     // "World"   β€” last 5 characters
substr($s, 6, 3);   // "Wor"     β€” start 6, length 3

5. ASCII / Character Codes

ord('A');   // 65
ord('a');   // 97
ord('0');   // 48
ord('Z');   // 90

chr(65);    // 'A'
chr(97);    // 'a'

// Convert lowercase letter to uppercase
$c = 'e';
echo chr(ord($c) - 32); // 'E'

// Check if character is letter
$c = 'a';
echo ($c >= 'a' && $c <= 'z') ? 'lowercase' : 'not lowercase';

// Frequency count
$s = "hello";
$freq = array_fill(0, 26, 0);
for ($i = 0; $i < strlen($s); $i++) {
    $freq[ord($s[$i]) - ord('a')]++;
}
print_r($freq); // index 4=2(l), 7=1(h), 11=1(e), 14=1(o)

6. String Comparison

$a = "apple";
$b = "Apple";

$a === $b;                  // false (case-sensitive)
strtolower($a) === strtolower($b); // true

strcmp($a, $b);             // > 0 (a > A in ASCII)
strcasecmp($a, $b);        // 0 (equal ignoring case)

// Compare for sorting
usort($words, 'strcmp');
usort($words, 'strcasecmp');

7. Common String Operations

$s = "  Hello World  ";

// Trim whitespace
trim($s);        // "Hello World"
ltrim($s);       // "Hello World  "
rtrim($s);       // "  Hello World"

// Case
strtolower($s);  // "  hello world  "
strtoupper($s);  // "  HELLO WORLD  "
ucfirst("hello world"); // "Hello world"
ucwords("hello world"); // "Hello World"

// Reverse
strrev("hello"); // "olleh"

// Repeat
str_repeat("ab", 3); // "ababab"

// Count
strlen("hello");           // 5
substr_count("hello", "l"); // 2

8. Searching in Strings

$s = "Hello World";

strpos($s, "World");       // 6 (first occurrence, case-sensitive)
stripos($s, "world");      // 6 (case-insensitive)
strrpos($s, "l");          // 9 (last occurrence)

// ⚠️ Use strict comparison β€” strpos can return 0 (falsy!)
if (strpos($s, "Hello") !== false) {
    echo "Found!";
}

// PHP 8.0+ β€” cleaner
str_contains($s, "World");   // true
str_starts_with($s, "Hello"); // true
str_ends_with($s, "World");   // true

9. Split and Join

// Split string into characters
$chars = str_split("hello");     // ['h','e','l','l','o']

// Split into chunks of size 2
$chunks = str_split("hello", 2); // ['he','ll','o']

// Split by delimiter
$parts = explode(",", "a,b,c");  // ['a','b','c']
$parts = explode(",", "a,b,c", 2); // ['a','b,c'] β€” limit

// Join array into string
implode(",", ['a','b','c']); // "a,b,c"
implode("",  ['h','i']);     // "hi"

10. Replace and Modify

$s = "Hello World";

// Simple replace (returns new string)
str_replace("World", "PHP", $s);   // "Hello PHP"
str_ireplace("world", "PHP", $s);  // "Hello PHP" (case-insensitive)

// Pad string
str_pad("5", 3, "0", STR_PAD_LEFT); // "005"

// Wrap long lines
wordwrap("The quick brown fox", 10, "\n", true);

11. Regular Expressions

$s = "PHP version 8.2";

// Match
preg_match('/\d+\.\d+/', $s, $m);
echo $m[0]; // "8.2"

// Match all
preg_match_all('/\d+/', $s, $matches);
print_r($matches[0]); // ['8', '2']

// Replace
preg_replace('/\d+/', 'X', $s); // "PHP version X.X"

// Split
preg_split('/\s+/', "a  b   c"); // ['a','b','c']

12. Key Patterns for Interviews

Pattern 1 β€” Two Pointers (Palindrome)

function isPalindrome(string $s): bool {
    $lo = 0;
    $hi = strlen($s) - 1;
    while ($lo < $hi) {
        if ($s[$lo] !== $s[$hi]) return false;
        $lo++;
        $hi--;
    }
    return true;
}
echo isPalindrome("racecar") ? 'yes' : 'no'; // yes

Pattern 2 β€” Frequency Map (Anagram)

function isAnagram(string $a, string $b): bool {
    if (strlen($a) !== strlen($b)) return false;
    $freq = array_fill(0, 26, 0);
    for ($i = 0; $i < strlen($a); $i++) {
        $freq[ord($a[$i]) - ord('a')]++;
        $freq[ord($b[$i]) - ord('a')]--;
    }
    foreach ($freq as $v) if ($v !== 0) return false;
    return true;
}
echo isAnagram("listen", "silent") ? 'yes' : 'no'; // yes

Pattern 3 β€” Sliding Window (Longest No-Repeat)

function lengthOfLongestSubstring(string $s): int {
    $map = [];
    $max = 0;
    $left = 0;
    for ($right = 0; $right < strlen($s); $right++) {
        $c = $s[$right];
        if (isset($map[$c]) && $map[$c] >= $left) {
            $left = $map[$c] + 1;
        }
        $map[$c] = $right;
        $max = max($max, $right - $left + 1);
    }
    return $max;
}
echo lengthOfLongestSubstring("abcabcbb"); // 3

Common Mistakes

MistakeProblemFix
if (strpos($s, $x))Returns 0 when found at index 0, which is falsy!== false
strlen on UTF-8Counts bytes not charsUse mb_strlen
Concatenating in loopO(nΒ²) due to string creationUse array + implode
Comparing ==Loose type, "1" == trueUse ===
Modifying $s[$i] in loopCreates copy, doesn't mutateWork with char array, then implode