alexso
alexso

Reputation: 163

If index is larger than length

I'm trying to get one character from a string. I can use an index which is larger than strlen as in the example below: (index: 9)

$string = "abcd";
echo substr($string, 9, 1);
//necessary result: b
//str: abcd abcd ab <-- b
//idx: 0123 4567 89 <-- 9

It can not be used substr probably, OK. But Im not sure...

Upvotes: 1

Views: 56

Answers (1)

Nick
Nick

Reputation: 147216

You could take the modulo of the index with the string length, and that will give you the effect of wrapping the string:

$string = "abcd";
echo substr($string, 9 % strlen($string), 1);

Output:

b

Demo on 3v4l.org

Upvotes: 5

Related Questions