Programming Fundamentals/Strings/PHP

strings.php

edit
<?php

// This program splits a given comma-separated name into first and last name
// components and then displays the name.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/PHP_Programming

function get_name()
{
    do
    {
        echo "Enter name (last, first):\n";
        $name = readline();
        $index = strpos($name, ",");
    } while ($index === FALSE);
    
    return $name;
}

function get_last($name)
{
    $index = strpos($name, ",");
    if ($index === FALSE)
    {
        $last = "";
    }
    else
    {
        $last = substr($name, 0, $index);
    }
    
    return $last;
}

function get_first($name)
{
    $index = strpos($name, ",");
    if($index === FALSE)
    {
        $first = "";
    }
    else
    {
        $first = substr($name, $index + 1);
        $first = trim($first);
    }

    return $first;
}

function display_name($first, $last)
{
    echo "Hello " . $first . " " . $last . "!\n";
}

function main()
{
    $name = get_name();
    $last = get_last($name);
    $first = get_first($name);
    display_name($first, $last);
}

main();

?>

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own PHP compiler / interpreter / IDE.

See Also

edit