Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats The use of function strtok() in PHP, how is better than other string function doing the same thing?

Tags:

Whats the use of function strtok() in PHP? How is better than other string function doing the same thing?

like image 571
OM The Eternity Avatar asked Mar 27 '10 04:03

OM The Eternity


People also ask

What is the use of strtok in PHP?

The strtok() function splits a string into smaller strings (tokens).

What does strtok return?

strtok() returns a NULL pointer. The token ends with the first character contained in the string pointed to by string2. If such a character is not found, the token ends at the terminating NULL character.

Does strtok allocate memory?

It is important to not that strtok does not allocate memory and create new strings for each of the tokens it finds. All the data still resides in the original string. Whenever strtok is called, it continues from where it left off and skips separators until it gets a valid character.

Is strtok thread safe?

strtok is neither thread safe nor re-entrant because it uses a static buffer while parsing. This means that if a function calls strtok , no function that it calls while it is using strtok can also use strtok , and it cannot be called by any function that is itself using strtok .


1 Answers

There is no other string function that does the same thing. Functions like explode return the complete split string in an array. strtok on the other hand only returns one piece at a time, with each subsequent call returning the next piece. This is potentially much more economic and memory preserving for large strings.

like image 199
deceze Avatar answered Nov 20 '22 20:11

deceze