Search code examples
phpstringunset

unset string offset in php


I'm trying to delete the letter p at the offset 1 of the below string.

$str = "apb";
unset($str[0]);
var_dump($str);

I'm getting a fatal error saying Cannot unset string offsets. Any suggestions?


Solution

  • Unset is there to unset the variable:

    $str = "apb";
    echo $str;
    unset($str);
    echo $str; // Undefined variable
    

    Str_replace is a easy way to do, what you want. Replace "p" with "":

    $newStr = str_replace("p", "", $str);
    echo $newStr;