Find the length of last word - coding interview question

    By: Thad Mertz
    1 month ago
    Category: PHPViews: 29

    Ok in this guide we are going to see how to find the length of last word. here is the code and i explain it step by step

        


    $string =  "hello world";
    $string =  "hello world wow";
    // get the length of last word.
    $charFound = 0;
    $stringsArray = [];
    for($i = 0; $i < strlen($string); $i ++)
    {
        if($string[$i] == " ")
        {
            $stringsArray[] = $charFound;
            $charFound = 0;
        }
        elseif (strlen($string) -1  == $i)
        {
            $stringsArray[] = ++$charFound;
            $charFound = 0;
        }
        else
        {
            $charFound++;
        }
    }

    var_dump($stringsArray);