0

According to the substr() manual

If string is less than offset characters long, an empty string will be returned.

But with negative offset

substr("abc",-9,1) 

the function returns

a

Mathematically speaking, a negative is always less than any string length of course, so there's no conflict with the above, but why doesn't it return an empty string though, in this direction, too? Is there a workaround without checking the length first?

https://onlinephp.io?s=s7EvyCjg5UpNzshXKC5NKi4p0lBKTEpW0tG11DHUVLAGAA%2C%2C&v=8.2.1

Szél Lajos
  • 449
  • 4
  • 11
  • 1
    Your string is 3 characters long, which is _more_ than -9. `substr("abc",9,1);` will return an empty string – brombeer Jan 23 '23 at 09:34
  • 1
    @brombeer As the question says, there's no contradiction in the description, but it might be expected that going "past the beginning" of the string (negative offset with magnitude greater than string length) has the same effect as going "past the end" (positive offset with magnitude greater than string length). – IMSoP Jan 23 '23 at 09:37
  • 2
    That said, I agree that "why" is likely to be hard to answer, and I'm not sure what kind of "workaround" there could be. That's what that function does, if you need something different, you'll need to write some custom code. – IMSoP Jan 23 '23 at 09:38
  • @IMSoP True, I misread the question, was confused by the first part. Thanks – brombeer Jan 23 '23 at 09:41
  • 3
    Look at it this way, you can not start returning characters from the 9th position of `abc`, because that has only 3 characters. But if you go in the other direction, `-9` - then there's six "positions" where there aren't any characters first, but then three positions where there _are_. So this could be considered a "graceful fallback" in this instance, whereas in the `+9` direction there simply is nothing to fall back onto to begin with. – CBroe Jan 23 '23 at 09:42
  • @CBroe Hm, that's a good point, the situations aren't symmetrical: you could think of there being an infinite number of empty strings after offset 3, but if you picture that with a negative offset, then start moving forward to take your substring, you eventually get back to the real string. – IMSoP Jan 23 '23 at 09:47
  • @CBroe that makes sense. Anyway I think I'll simply use strrev() and positive offset. – Szél Lajos Jan 23 '23 at 09:47
  • strrev is a costly operation. I'd stick with a ternary and strlen – Your Common Sense Jan 23 '23 at 10:48

0 Answers0