strtok() Function Use in PHP 8.4 and PHP 8.5

The strtok() function behaves identically in PHP 8.4 and PHP 8.5. There are no version-specific changes to this function in either release. The most recent changelog entry for strtok() dates back to PHP 8.3.0, which only added a warning when the delimiter is missing.

strtok() Function

strtok() splits a string into smaller strings (tokens) based on a set of delimiter characters. Its key characteristic is that it is stateful: the first call initializes the string, and subsequent calls continue from where the last one left off.

Signature:

// First call (initializes and returns first token)
strtok(string $string, string $token): string|false

// Subsequent calls (only need the delimiter)
strtok(string $token): string|false

Example

Here is a common pattern for iterating through tokens using a while loop:

<?php
$string = "This is an example string";
// Use space, tab, and newline as delimiters
$tok = strtok($string, " ");

while ($tok !== false) {
   echo "Word={$tok} ";
   // Subsequent calls only pass the delimiter
   $tok = strtok(" ");
}
?>

Output:

Word=This
Word=is
Word=an
Word=example
Word=string

19 Views