I want to grab the last name or second word of this variable
$name = 'Sandra Bullok';
$first_token = strtok($name, ' ');
echo $first_token;
Will output "Sandra"
How can I output "Bullok"
$name = 'Sandra Bullok';
$parts = explode(' ', $name);
echo $parts[0]; // 'Sandra'
echo $parts[1]; // 'Bullok'
http://php.net/manual/en/function.explode.php
If You want to do this with strtok():
$name = 'Sandra Bullok';
$first_token = strtok($name, ' ');
$second_token = strtok(' ');
echo $first_token; // 'Sandra'
echo $second_token; // 'Bullok'
An alternative:
list($first, $last) = explode(' ', $name);
You can do some additional checking to see if how many there are as maybe there is a first, middle and last name.
If you want to use strtok
, you should do something like this:
$name = 'Sandra Bullok';
$token = strtok($name, ' ');
while ($token !== FALSE) { // enter all possible values
echo $token . ' ';
$token = strtok(' ');
}