December Code

PHP string interview questions, with answers

Most PHP code builds or parses strings: HTML, SQL, JSON, URLs and user input. Interviewers therefore ask about the string syntax PHP offers and about the functions that handle strings correctly: which quotes interpolate variables, how to embed long text, how to search and compare without surprises, and why a string's length is not always its number of characters.

The answers below cover quoting, heredoc and nowdoc, searching, comparison, splitting and joining, multibyte text and formatting, with code run on PHP 8.5. Then take the free PHP diagnostic — ten questions across every PHP topic in the bank — to see which of these you can explain but not yet predict.

The questions, with answers

  1. 1.What is the difference between single-quoted and double-quoted strings in PHP?

    In short: Double-quoted strings interpolate variables and understand escapes such as \n; single-quoted strings are literal apart from \' and \\.

    In a double-quoted string PHP replaces variables with their values and processes escape sequences, so "Hi $lang" prints Hi PHP and \n becomes a newline. A single-quoted string is taken literally: $lang and \n print as written, and only \' and \\ are escapes. Single quotes are therefore slightly simpler for fixed text, while double quotes suit messages with values in them; for an expression such as a property or array element, braces make the boundary explicit, as in "{$user->name}". Neither kind of string is faster in any way that matters today.

    $lang = "PHP";
    echo 'Hi $lang\n', PHP_EOL;
    echo "Hi $lang", PHP_EOL;
    // Hi $lang\n
    // Hi PHP
  2. 2.What are heredoc and nowdoc strings in PHP?

    In short: Heredoc (<<<ID) is a multi-line string that interpolates like double quotes; nowdoc (<<<'ID') is the multi-line form of single quotes.

    Heredoc syntax starts with <<< and an identifier, such as <<<TXT, and ends with the identifier alone, TXT; everything in between is the string, with variables interpolated as in double quotes. It suits long templates, SQL and HTML where quotes would otherwise need escaping. Nowdoc puts the identifier in single quotes, <<<'TXT', and then nothing is interpolated, like a single-quoted string. Since PHP 7.3 the closing identifier may be indented, and that indentation is removed from every line, so heredocs can follow the surrounding code's indentation.

    $n = 2;
    echo <<<TXT
    Items: $n
    TXT;
    // Items: 2
  3. 3.How do you check whether a string contains, starts with or ends with another in PHP?

    In short: Use str_contains, str_starts_with and str_ends_with, added in PHP 8, which return true or false.

    PHP 8 added three functions that answer these questions directly with a boolean: str_contains($haystack, $needle), str_starts_with and str_ends_with. They are case-sensitive and treat an empty needle as always found. Older code uses strpos, which returns the position of the first match or false, and stripos for a case-insensitive search; when a position is actually needed, those are still the tools, and substr extracts part of a string by offset and length. For patterns rather than fixed text, preg_match runs a regular expression.

    $url = "https://x.in/a";
    var_dump(str_starts_with(
        $url, "https"));
    // bool(true)
  4. 4.How do you compare strings in PHP?

    In short: Use === for exact equality, strcmp for ordering, and strcasecmp or strnatcmp when case or natural number order should be ignored.

    === compares two strings exactly, byte by byte. For ordering, strcmp returns a negative number, zero or a positive number depending on whether the first string sorts before, equal to or after the second; PHP 8.2 made it return exactly -1, 0 or 1. strcasecmp does the same ignoring ASCII case, so "HI" and "hi" compare as equal. strnatcmp uses natural order, so "img10" sorts after "img9", which a plain comparison gets wrong. Comparing strings with == works for exact matches but applies numeric comparison when both strings look numeric, so "1e3" == "1000" is true.

    echo strcmp("a", "b"), " ";
    echo strcasecmp("HI", "hi");
    // -1 0
  5. 5.How do you split a string into an array and join an array into a string in PHP?

    In short: explode splits a string on a separator into an array; implode joins an array's elements with a separator into a string.

    explode($separator, $string) returns an array of the pieces between separators, so a comma-separated line becomes an array of fields; an optional limit caps the number of pieces. implode($glue, $array) does the reverse, joining the elements with the glue string. For splitting on patterns, preg_split takes a regular expression, and str_split breaks a string into fixed-length chunks. For real CSV data with quoted fields, str_getcsv or fgetcsv parse correctly where explode would split inside quotes.

    $csv = "red,green,blue";
    $parts = explode(",", $csv);
    echo count($parts), " ";
    echo implode("|", $parts);
    // 3 red|green|blue
  6. 6.Why does strlen not count characters in a UTF-8 string?

    In short: strlen counts bytes, and UTF-8 characters outside ASCII take several bytes; mb_strlen or a Unicode-aware function counts characters.

    PHP strings are byte arrays with no built-in encoding, so strlen returns the number of bytes. In UTF-8, é takes two bytes, so strlen("café") is 5 even though the word has four characters. Counting or slicing characters needs an encoding-aware function: the mbstring extension provides mb_strlen, mb_substr and mb_strtoupper, and the PCRE functions work on characters when a pattern has the u modifier, which is how preg_match_all counts 4 below. Byte-based functions such as substr can cut a character in half and produce invalid UTF-8.

    $s = "café";
    echo strlen($s), " ";
    echo preg_match_all(
        '/./u', $s);
    // 5 4
  7. 7.How do you format strings with sprintf and printf in PHP?

    In short: sprintf returns a string built from a format with placeholders such as %d, %s and %.2f; printf prints the same thing directly.

    A format string contains literal text and conversion specifications starting with %. %d formats an integer, %s a string, %f a float, %x hexadecimal and %b binary, and each can take a width, padding and precision: %05.1f pads to five characters with zeros and one decimal place, and %-4s left-aligns a string in four characters. sprintf returns the result and printf prints it, while number_format adds thousands separators. Formatting with placeholders keeps output readable and avoids long chains of concatenation.

    printf("%05.1f|%-4s|%x",
        3.14159, "ab", 255);
    // 003.1|ab  |ff

How the diagnostic asks it

One question from the PHP bank, exactly as a sitting would show it. The bank has 3 on strings and 30 across PHP.

Strings · easyPHP-005

What does this PHP code print?

$n = 3;
echo 'n = $n', " | ", "n = $n";
  1. 1n = 3 | n = 3
  2. 2n = $n | n = $n
  3. 3n = $n | n = 3correct
  4. 4n = 3 | n = $n

In a single-quoted string PHP treats almost everything literally: only \' and \\ are escapes, so 'n = $n' prints the dollar sign and the name. A double-quoted string interpolates variables and understands escapes such as \n, so "n = $n" prints n = 3. The output is therefore n = $n | n = 3. n = 3 twice assumes both quotes interpolate, n = $n twice assumes neither does, and the last option has the two kinds of quote the wrong way round. For complex expressions inside a double-quoted string, braces help: "{$user->name}".

Measure it

Reading answers tells you what’s true. A diagnostic tells you what you get wrong.

10 PHP questions across its topics, easy to hard, about fifteen minutes. You get a readiness figure with the arithmetic shown, the topics you missed named, and a practice set sized for today. Free: 1 diagnostic a month and 15 problems a day. No card.

What the readiness test measures · how the score is computed

By Harshit · updated