0

How can you convert a string that contains your first and last name and sometimes middle name into an array with this format?

customFunction('Chris Morris');
  // array('firstname' => 'Chris',     'lastname' => 'Morris')
customFunction('Chris D. Morris');
  // array('firstname' => 'Chris D.', 'lastname' => 'Morris')
customFunction('Chris');
  // array('firstname' => 'Chris',  'lastname' => '')
0

3 Answers 3

2

Try this

function splitName($name){
  $name = explode(" ",$name);
  $lastname= count($name)>1 ? array_pop($name):"";
 return array("firstname"=>implode(" ",$name), "lastname"=>$lastname);

}
Sign up to request clarification or add additional context in comments.

Comments

1

you can try this:

 <?php
    $arr = 'Chris D. Morris';
   function customFunction($str){
    $str = trim($str);
    $lastSpace = strrpos($str," ");
    if($lastSpace == 0){
        $first = $str;
        return array('firstname' => $first, 'lastname' => $last);
    }else{
    $first = substr($str, 0, $lastSpace);
    $last = substr($str,$lastSpace);
    return array('firstname' => $first, 'lastname' => $last);
    }
}
    $got = customFunction($arr);
    print_r($got);
    ?>

hope it helps.

Comments

0
function parseName($input) {

    $retval = array();
    $retval['firstname'] = '';
    $retval['lastname'] = '';

    $words = explode(' ', $input);
    if (count($words) == 1) {
        $retval['firstname'] = $words[0];
    } elseif (count($words) > 1) {
        $retval['lastname'] = array_pop($words);
        $retval['firstname'] = implode(' ', $words);
    }

    return $retval;
}

2 Comments

I get Array to string conversion when passing the string to the function.
Just fixed it... Although I see two other solutions which are much shorter. I'd use one of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.