How turn one variable into two in PHP

I have a form that only has one field for name and I want to get the two values submitted and store first and last as seperate values in the database. How would I do that?

<?php
$name
= $_POST['name'];
...
?>

Your rating: None Average: 5 (1 vote)

Replies

explode

5

You would explode the variable

$data = explode(' ',$name);
$data[0] would contain the first value
$data[1] would contain the last value

Unless they submitted a string with lots of spaces you would lose everything after the second string.
$data = explode(' ',$name,2);

The ,2 will make so all of the string after the first will be kept in the second value $data[1];

You could also pass it to list to assign the first and se

say the name is 'John Bob Doe'
$name = $_POST['name'];
list($first,$last) = explode(" ", $name,2);

$first would equal 'John'
$last would equal 'Bob Doe'

(You should also filter your $_POST values as you never know what the user may be entering)

Your rating: None

Post new comment

 
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><code>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters (without spaces) shown in the image.