2

There is this post:

PHP Subtract First Character of String

It advices me to use substr(...);

I want to keep a rolling text to log if an error occurs, (The 1000 latest characters from a stream) but it seems like there would be a better way than to create a 1000 character string from a 1001 character string, then assigning that string to the latter.

I will be doing this in a very tight loop, so performance should not be negligible (even though I haven't measure this yet).

Is there any way to delete first character of a string in-place?

2 Answers 2

1

This should work properly but not a good choice

<?php
    $str = '12345678';
    $str[0] = null;
    echo $str; // output: 2345678
?>

Since

echo strlen($str); // output: 8 because first character is not deleted, it is "hidden"

Take me over 500 points if this is helpful (:

Sign up to request clarification or add additional context in comments.

2 Comments

Hrumf, I might do something similar in the end (iterate over string, setting [n] = [n + 1]). Should be better than copying the string for every single character...
What do you mean by "copying the string for every single character"? Anyway, I think the use of substr() is not that bad :) No need to use a loop this problem.
0

The obvious question would be why you would want to do this in PHP? You probably have operating system support for rolling logs.

However, if you wish to have a robust solution you are most likely best off using substr.

Another option could be to use the array access for a string:

unset(your_string[0]);

1 Comment

How can you unset a string offset?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.