Strpos(): needle is not a string or an integer

Hello,

I’m working on a PHP discord bot. I have a function that searches an array. When I run the code below, I get these errors:

Warning: strpos(): needle is not a string or an integer
PHP Warning:  strpos(): needle is not a string or an integer on line 22

I’m a little bit confused as $message is a string. Any ideas?

$discord->on('ready', function ($discord) {
    // We are ready!

    // Listen for events here
    $discord->on('message', function ($message) {
        $list = array(
            "join my server"
        );
        $content = $message["content"];
        foreach($list as $lists){
            if (strpos($content, $list) == true) {
                echo "LOG: User is flagged.";
            }
        }
    });
});

The error is complaining about the strpos() second parameter $list not being a string or integer. I suspect you wanted to use $lists here, not $list?

I had another look at the code and I belive that it is complaining about the variable $message["content"]. I don’t see why this isn’t a string because it is just pulling a value from an array.

Which line is line 22?

If you believe that, then print out the value of gettype ($content) and see what it is.

From the docs:

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

So the second argument is the one at fault. As previously pointed out, an array is being passed to it. Hence the error.

Again per the docs:

needle
If needle is not a string, it is converted to an integer 
and applied as the ordinal value of a character. 
This behavior is deprecated as of PHP 7.3.0, and 
relying on it is highly discouraged. 
Depending on the intended behavior, 
the needle should either be explicitly cast to string, 
or an explicit call to chr() should be performed.
1 Like

Bit of an update: somehow the code just started working for me.

Also: Do not use

Unless you are very sure that’s what you want. strpos(“Thing a different deer”,“Thing”) will return 0 - 0 != true, but you found the string.

If you’re looking to see if the strpos found the string or not, explicitly and strictly check for FALSE:
strpos($x,$y) !== FALSE (if trying to say ‘if found’)

Right now your if check says “If the string was in the string and not the beginning of the string.”

2 Likes