开发者

Why can i not send a string but only a number to a member function?

Im making my own function to search for the total number of something. but it is not working propperly. function getNumberOfCounts gets the $fromIndex but not the searchWord

开发者_如何转开发public function getNumberOfCounts( $searchWord, $fromIndex )
{       
    $index = $fromIndex;
    $counter = 0;

    while( $index <= $endPos )
    {
        $index++;

        $pos = strpos( $this->text, $searchWord, ($index+1) );

        if( $pos > $index )
        {
            $counter++;

            $index = $pos;
        }
        else
            break;

    }

    return $counter;
}

public function searchDemo()
{
    $startPos = 11; // ex

    echo "<br /> count= " . $this->getNumberOfCounts( "Lorem", $startPos );
}

They are both part of the same class ofc.

EDIT: i know there is some missing info, but if I try to print $searchWord on the first line of getNumberOfCounts nothing is outputted.


You will likely have less problems and better performing code when just using

  • substr_count — Count the number of substring occurrences


You're starting from position 11 for starters, which would be greater than the total length of "Lorem". Secondly, in your while loop, you're running while startpos < endpos. $endpos hasn't been assigned a value yet, so it's not even entering the loop.

While I'm at it, you're incrementing index at the start of the loop (probably not desired). It's usually the case the the index is incremented at the end of the loop, so you can use the index to "index into" an array without having to shift position.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜