Search code examples
phppreg-match

Undefined offset in PHP


When I tried following code:

function getusername($input){
    //parse the result
    preg_match("/<username>(.*)?<\/username>/", $input, $username);
    return $username[1]; // Line 4
}  

It gave me this error:

Undefined offset on line 4.


Solution

  • What blunder am I doing ?

    Well, it seems $username[1] does not exist. This might happen if the regular expression does not match. I would change it to:

    function getusername($input){
        preg_match("/<username>(.*)?<\/username>/", $input, $username);
        if( count( $username ) > 0 ) {
            return $username[1];
        }
        return false;
    }