Hey all. I need to create an array of first names from another array of first and last names. So basically the original array with first and last names looks like this:
Original Array
array("John Doe", "Jane Doe", "John Darling", "Jane Darling");
And the array I need to create from that would be:
New Array
array("John", "Jane", "John", "Jane");
So I gues开发者_如何学Pythons for each value I would need to remove whatever comes after the space. If someone can point me in the correct direction to use regular expressions or some array function that would be great.
Cheers!
Update: Thank you all for your answers.
You can create a callback function that strips the last names, and map it to the array, like so (I use a different approach rather than explode()
, both are equally valid methods):
function strip_last_name($name) {
if (($pos = strpos($name, ' ')) !== false) {
// If there is at least one space present, assume 'first<space>last'
return substr($name, 0, $pos);
} else {
// Otherwise assume first name only
return $name;
}
}
$first_names = array_map('strip_last_name', $full_names);
This preserves the array keys and the order of elements.
this should do the trick, and if it shouldn't I'm really sorry but haven't slept this night :P, but you'll get the idea ;)
<?php
$secondarray=array();
foreach($firstarray as $fullname){
$s=explode(' ',$fullname);
$secondarray[]=$s[0];
}
?>
$array1 = array("John Doe", "Jane Doe", "John Darling", "Jane Darling");
$array2 = array();
foreach ($array1 as $name) {
$firstname = explode(' ',$name);
$array2[] = $firstname[0];
}
The explode
function splits a string by a delimiter, for example explode('b','aaaaabccccc')
returns array('aaaaa','ccccc')
. The above code uses this, with a foreach loop, to split each full name into an array containing the first and last name, and then add the first name to an array like the first one.
精彩评论