Split Comma Separated Names with PHP - php

I have names in the form of Lastname, Firstname. In my database I have a different field for both the first and last.
I would like to use PHP to read everything before the comma as the lastname and everything after the comma as the firstname. What is the best way to accomplish this?

list($Lastname,$Firstname) = explode(",",$Name);

<?php
$names = explode( "," , $allNames);
// $names[0] and names[1] are first and last names
?>

with the explode function.
<?php
list($firstname, $lastname) = explode(',','Lastname, Firstname',2);
echo $firstname.' '.$lastname;
?>

If you'll use list();
while( list($fname,$lname) = explode(", ", $db->fetch() ) ) {
echo $lname . " " . $fname . "<br />";
}
Without list() and assining an array;
$name = explode( ", ", $db->fetch()->nameField );
// may be you want to do something with that array
// do something
// echoing
foreach( $name as $fname=>$lname ) {
echo $lname . " " . $fname . "<br />"
}

As nobody has mentioned it yet, to expressly meet the question requirements, you'll need to use the third parameter to explode()
list($lastname, $firstname) = explode(',', $name, 2);

Related

can't get ucfirst() to work on a variable

I have made a code that takes the first name and last name from an email, the $firstname is uppercase but $lastname is not. Why?
<html>
<body>
<?php
$email = "test.testt#testing.com";
$firstname = ucfirst(strtok(strtok($email, "#"), "."));
$lastname = substr(strtok(strtok($email, "#"), ".") . ' ' . strtok("."), strrpos(strtok(strtok($email, "#"), ".") . ' ' . strtok("."), ' '));
$lastname = ucfirst($lastname);
echo $firstname.$lastname;
?>
</body>
</html>
Output: Test testt
any help would be greatly appreciated
Besides the actual problem being the space, your code does a lot of searching and chopping strings up.
You could simplify it by using explode() with first the # and then a .. Then using ucfirst on each part of the last operation...
$names = explode("#", $email);
// Get first 2 parts of name and split it by the .
[$firstname, $lastname] = explode(".", $names[0], 2);
$firstname = ucfirst($firstname);
$lastname = ucfirst($lastname);
echo $firstname . ' ' . $lastname;
The space was indeed the problem, I fixed it by using $lastname = ucfirst(str_replace(' ', '', $lastname));

Foreach loop inside foreach loop?

I have a list of names and each name consist of 2-4 words: name, (if exist) middle name(s), surname.
These are the names:
Ali Yilmaz
Taha Ugur Unal
Omer Ibrahim Tahsin Son
Recai Sahin
etc.
I want to print this names as this: Surname, name middle name(s) (if exist)
The names above will be:
Ali Yilmaz -> Yilmaz, Ali
Taha Ugur Unal -> Unal, Taha Ugur
Omer Ibrahim Tahsin Son -> Son, Omer Ibrahim Tahsin
Recai Sahin -> Sahin, Recai
etc.
If I had only one name I can use that code:
<?php $exp1 = explode(" ", $author1); ?>
<?php if (count($exp1) == 2) {?>
<?php print ($exp1[1] .', ' .$exp1[0]); ?>
<?php } elseif (count($exp1) == 3) {?>
<?php print ($exp1[2] .', ' .$exp1[0] .' ' .$exp1[1]); ?>
<?php } elseif (count($exp1) == 4) {?>
<?php print ($exp1[3] .', ' .$exp1[0] .' ' .$exp1[1] .' ' .$exp1[2]); ?>
<?php }?>
Each page can have different numbers of author and I thought I could use foreach to apply the above code for each author name but I couldn't do this.
I tried a piece of code such that:
<?php foreach $author as $obj): ?>
<?php $a = explode (" ", $obj) ?>
<?php endforeach ?>
...
But it gives error:
explode() expects parameter 2 to be string, array given.
How can I do this?
<?php
$names = array(
'Ali Yilmaz',
'Taha Ugur Unal',
'Omer Ibrahim Tahsin Son',
'Recai Sahin'
);
// First you should iterate through:
foreach ($names as $name) {
// and now, let make the job
// split by words
$parts = explode(' ', $name);
if (count($parts) == 1) {
echo "{$name}<br/>";
continue;
}
// get last word
$last = array_pop($parts);
// Print last one, comma, and rest of name
echo "{$last}, " . implode(' ', $parts) . "<br/>";
}
If you had a single string, you would
split all the words with explode().
take out the surname and store it.
join the rest of the name with implode().
See the example below:
<?php
$name = "Son of the Mask";
$words = explode(" ", $name); // split the string wherever there is a whitespace.
$surname = array_pop($words);
$restOfTheName = implode(" ", $words); // join the words with a whitespace in between them.
echo $surname . ", " . $restOfTheName;
?>
On the other hand, if you have a list of names in an array called, say, $namelist, you can use the foreach() loop to iterate through the list.
You would do something like:
<?php
foreach ($namelist as $name)
{
$words = explode(" ", $name);
$surname = array_pop($words);
$restOfTheName = implode(" ", $words);
echo $surname . ", " . $restOfTheName;
}
?>
Hope that helped :-)
EDIT:
And no, you need not use <?php and ?> on every line. This is only helpful, say when you want to use small snippets of PHP inside your HTML tags.
For example, let us say you want to display some information in an unordered list. Then you would do something like
<?php
$info1 = "Head over to Google.com";
$info2 = "Search before you post!";
?>
<ul>
<li><?php echo $info1; ?></li>
<li><?php echo $info2; ?></li>
</ul>
But, doing this for a script that contains only PHP code doesn't make sense. Moreover, it renders your code difficult to read, and eats up a lot of your valuable time.
you can try this
<?php
$newNameArray=array();
$namesArray = array(
'Ali Yilmaz',
'Taha Ugur Unal',
'Omer Ibrahim Tahsin Son',
'Recai Sahin'
);
foreach ($namesArray as $name) {
$partsOfName = explode(" ", $name);
//last name
$lastName = array_pop($partsOfName);
// store the name in new array
$newNameArray[]=$lastName.", ".implode(" ", $partsOfName);
}
//show all names
var_dump($newNameArray);
?>
you can see this for details explode and array push
use this
foreach ($author as $obj) {
$nameArr = explode(' ',$obj);
if(count($nameArr) > 1) {
$lname = $nameArr[count($nameArr)-1];
array_pop($nameArr);
echo $lname.", ".implode(' ',$nameArr);
echo "<br />";
} else {
echo $obj;
echo "<br />";
}
}

double quotes inside single quotes in MYSQL result?

I'm trying to do something very basic but I can't figure out how.
basically i'm trying to convert the mysql result ($row) into the following format (literal strings):
"0784562627828" => "James",
"0786636363663" => "David",
I have all the data stored in the database and I can get them echoed on my page like so:
$phone = $row['phone'];
$name = $row['name'];
$list .=''.$phone.'';
echo $list;
could someone please advise on this?
Thanks
Just assign them inside an array like you normally would:
$array = array();
while(your fetch here) {
$array[$row['phone']] = $row['name'];
}
To check its contents, you can use var_dump($array) or print_r($array)
Or just straight up show them, like the one you formatted:
while(your fetch here) {
echo '"' . $row['phone'] . '"' . ' => ' . '"' . $row['name'] . '"' . '<br/>';
}
you mean something like this?
$list = array();
$list[$phone] = $name;
Can you do something like
$list = [];
foreach($rows as $row) {
$list[$row['phone']] = $row['name'];
}

Random array, showing less than 3 of the same

I am using a random PHP array for a raffle type script and I sometimes get the same string 3 or more times. How can I limit the random to only show a max of 2 of the same string?
For example I have:
<?php
$raffle = array('string1', 'string2', 'string3', 'string4', 'string5', 'string6');
echo $raffle[array_rand($raffle)] . ", " . $raffle[array_rand($raffle)] . ", " . $raffle[array_rand($raffle)] . ", " . $raffle[array_rand($raffle)];
?>
So it chooses a random of 4 strings from the array, but I don't want the same string to show up more than twice. How can I achieve this?
Below is a function that will store what has been pick, and if picked again, remove it from the array. Once removed from the array, it'll never get picked again. So items can show up twice, but not more:
function pull_raffle() {
static $raffle = array('string1', 'string2', 'string3', 'string4', 'string5', 'string6');
static $pulled_before = array();
$pick = array_rand($raffle);
$string = $raffle[$pick];
if (array_key_exists($string, $pulled_before)) {
unset($raffle[$pick]);
} else {
$pulled_before[$string] = true;
}
return $string;
}
Use it like this:
echo pull_raffle() . ", " . pull_raffle(). ", " . pull_raffle() . ", " . pull_raffle();

do not write empty array fields

ik have a html form where i can select some options. I want to write those values comma separated to my database. This is the code i have
$genretotal = $_POST['genre'];
$genre0 = $genretotal[0];
$genre1 = $genretotal[1];
$genre2 = $genretotal[2];
$genre3 = $genretotal[3];
$genre4 = $genretotal[4];
$genre5 = $genretotal[5];
$genre6 = $genretotal[6];
$genre7 = $genretotal[7];
$genre = $genre0 . "," . $genre1 . "," . $genre2 . "," . $genre3 . "," . $genre4 . "," . $genre5 . "," . $genre6 . "," . $genre7;
How can i leave out the empty values?
Try with implode and array_filter
implode(',', array_filter($_POST['genre']));
Why so?
$genre = join(',', array_filter($_POST['genre'], function($sItem)
{
//here I assume your 'not empty' matches PHP empty() function
//if not, then add desired conditions
return !empty($sItem);
}));
$genretotal = $_POST['genre'];
if(isset($genretotal) && count($genretotal)>0)
{//This check array is null or not
$gen_arr = implode(",",$genretotal);
}//end if
echo $gen_arr;
//This is the code you avoid empty values

Categories