Nurettin Kaya
Nurettin Kaya

Reputation: 13

php strpos offset outputs different

What is it that causes this difference?

echo strpos('abcdef abcdef', 'a', 0); //output= 0
echo strpos('abcdef abcdef', 'a', 1); //output= 7
echo strpos('a b- c a b* c a b+ c', 'c', 0); //output= 5 
echo strpos('a b- c a b* c a b+ c', 'c', 1); //output= 5 (But why? Is is must be 12)
echo strpos('a b- c a b* c a b+ c', 'c', 6); //output= 12

Upvotes: 0

Views: 1495

Answers (2)

Marc B
Marc B

Reputation: 360712

The 3rd argument is the starting location, not the number of found characters to skip. e.g.

strpos('...', 'a', 0)   option #1
strpos('...', 'a', 1)   option #2

abcdef abcdef
0123456789111
↑↑        012
││
└┼─ option #1: start at position 0('a'), and boom, find an 'a'
 └─ option #2; start at position 1('b'), find 'a' at position 7

So for your a b- c a b* c a b+ c string, the second version only skips 1 character, leaving the first c to be found at position 5:

a b- c a b* c a b+ c
01234567891111111111
↑↑    ↑   0123456789
││    │
└┼────┼─ start at position 0, first C at position 5
 └────┼─ start at position 1, first C still at 5
      └─ start at position 6, first C now at 12

Upvotes: 4

Volker Schukai
Volker Schukai

Reputation: 166

you use search offset 1 (start search one character from left) and therefore the first c is on position 5

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

Find the numeric position of the first occurrence of needle in the haystack string.

offset If specified, search will start this number of characters counted from the beginning of the string. Unlike strrpos() and strripos(), the offset cannot be negative.

echo strpos('a b- c a b* c a b+ c', 'c', 1); //output= 5 (But why? Is is must be 12)

             0123456789111
              ^        012
              | your offset (start search 'c')

http://php.net/manual/de/function.strpos.php

Upvotes: 1

Related Questions