Explode a fullname in a variable

I’m trying to extract a full name from a field in a table, explode it into a two element variable and then insert it into first name/last name fields in the table.

I’m using some code which is giving me an error because my two word string is in a variable and explode thinks it is only one argument when it expects two. Can anyone help me figure out how to do this?



require '__classes/Db.php';
$sql = "SELECT name FROM tbl_persons";
$stmt = $pdo->query($sql);
$row = $stmt->fetchall(PDO::FETCH_ASSOC);

foreach ($row as $name) {
    $names = explode($name['name']);

The explode function requires a minimum of 2 parameters: Separator and String. Limit is an optional third.
So you first need to give it the string that separates the two words, be that a space, or whatever.

For example, if the names are separated by a space:-

$string = 'John Doe' ;

You must tell explode that a space separates the parts of the string you want to explode:-

$names = explode(' ', '$string);

PHP: str_word_count - Manual

Perfect. Thanks --Kenoli

The real problem is that the full name is stored together in the same column. You should have first_name, last_name, middle_name columns. It would be a trivial query to put it together any way you want without code.


It also centers around a fallacy that everyone has exactly two names.

“John Wilkes Booth”
“Jo Ann Smith”
“John Paul Jones”
“Martin Luther King Jr.”
“John Quincy Adams”
“Pope Alexander VI”
“Sir Baron Horatio Montigue”

1 Like