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 />";
}
}
Related
so my words is below, separated by space. my code is 1st line is grabbed from text file & whole line is echoed, instead i need each-word as ordered list.
• bombay new_delhi chennai culcutta
<?php
$z = file('q1.txt'); echo $z[1]; echo (mt_rand(1,9));
$st = array($z[1]);
foreach($st as $ls) {echo " <li>$ls</li>\n";}
i need like this
• bombay
• new_delhi
• chennai
• culcutta
Before the foreach()
echo '<ol>';
//foreach loop
echo '</ol>';
<?php
$z = file('q1.txt'); echo $z[1]; echo (mt_rand(1,9));
$c= explode(" ", $z[1]);
echo '<ol>';
foreach($c as $w) {echo " <li>$w</li>\n";}
echo '</ol>';
$var = file('q1.txt');
$abc = explode(' ', $var);
echo '<ul style=" list-style-type: circle;">';
foreach($abc as $value){
echo " <li>$value</li>";
}
echo '</ul>';
I have a variable that equals some simple data as shown below
$var = 'hello names here how are yous?';
what i wish to achieve is have a foreach loop inside the $var but i have tried various ways with just no luck, always throwing errors.
Below is somewhat what i what to do.
$var = 'hello '.foreach($datas as $data) { echo $data }.' how are yous?';
echo $var;
which would output - hello Mike Daniel Steve how are yous?
any help appreciated.
======EDIT========
im trying to write to file the looped contents with below code.
$datas = 'Name, Name2, Name4';
$var = ''.foreach($datas as $data) { echo $data }.'
$default_file = 'media/default.php';
$default_file_handle = fopen($default_file, 'w') or die('Cannot open file: '.$default_file);
$default_data = '
'.$var.'//each value to be a new line
Name2 //example
Name4 //example
etc
';
fwrite($default_file_handle, $default_data);
so basically im write to file each value in the loop to a new line. I can write just normal content but getting a loop in their im struggling with
$var = 'hello';
foreach($datas as $data) {
$var .= ' '.$data.' ';
}
$var .= ' how are you?';
echo $var;
that should do it
$arr = array("Mike", "John");
echo "Hello " . implode(" ", $arr) . ", how are you?";
implode is your friend. Implode joins array elements together into one single string. The separator between each array element is the first parameter - in this case a blank.
You can use implode:
$var = 'hello '.implode(' ', $datas) .' how are yous?';
echo $var;
To achieve this you either have to insert the foreach loop like this:
echo "hello ";
foreach($datas as $data) {
echo $data;
}
echo " how are you?";
or you can use an extra variable and the implode method:
$dataString = implode(" ", $datas);
echo "hello " . $dataString . " how are you?";
You can do this following way.
<?php
$data = array('Mike Daniel','john doe');
foreach ($data as $value) {
$result = 'hello '. $value. ' how are you?'. '</br>';
echo $result;
}
I have a field in my database with the text value:
"these, are, some, keywords" (minus the inverted commas)
Now, I wonder if I can generate an unordered list from this so ultimately my HTML reads:
<ul>
<li>these</li>
<li>are</li>
<li>some</li>
<li>keywords</li>
</ul>
Is this possible with PHP and if so is anyone able to help me out with this?
Many thanks for any pointers.
You can accomplish this with something like the following:
<?php
$yourList = "these, are, some, keywords";
$words = explode(',', $yourList);
if(!empty($words)){
echo '<ul>';
foreach($words as $word){
echo '<li>'.htmlspecialchars($word).'</li>';
}
echo '</ul>';
}
?>
As mentioned by elcodedocle, you may want to use str_getcsv() instead of explode if more appropriate.
Have a look at str_getcsv() and explode()
Example:
<?php
$mystring = "these, are,some , keywords";
$myvalues = str_getcsv($mystring);
$myoutput = "<ul>";
foreach ($myvalues as $value){
$myoutput .= "<li>".trim($value)."</li>\n";
}
$myoutput .= "</ul>";
echo $myoutput;
?>
You need to explode you string for ', '
print <ul>
for each element in the array you received you print '<li>' . $value . '</li>'
print </ul>
You can try:
$arr = explode(",","these, are, some, keywords");
$res = "<ul>";
foreach ($arr as $val){
$res .= "<li>" . $val . "</li>";
}
$res .= "</ul>";
echo $res;
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);
I loop through my array to print the articles names:
<?php
if ($articles) {
foreach($articles as $article) {
echo $article->name.", ";
} // end foreach article
} // end if has articles
?>
This will obviously produce something like
Apple, Banana, Mango,
But I am looking for:
Apple, Banana, Mango
I tried some implode statement like this:
<?php
if ($articles) {
foreach($articles as $article) {
echo implode(", ", $article->name);
} // end foreach article
} // end if has articles
?>
or
<?php
if ($articles) {
echo implode(", ", $articles->article->name);
} // end if has articles
?>
None of these are working for me. How can do it right? Thanks for hints!
You can use foreach to add the article names to an array, then implode() that array of names.
<?php
if ($articles) {
$article_names = array();
foreach($articles as $article) {
$article_names[] = $article->name;
} // end foreach article
echo implode(', ', $article_names);
} // end if has articles
?>
it's much more easy to check for your first loop-iteration, wrte the comma before your text and leave this comma aout on the first iteration:
<?php
if ($articles) {
$firstiteration = true:
foreach($articles as $article) {
if(!$firstiteration){
echo ", ";
}
$firstiteration = false;
echo $article->name;
} // end foreach article
} // end if has articles
?>
another (more beautiful in my optionion) possibility would be to override the _toSting()-method of your article-class:
...
function __toString(){
return $this->name;
}
...
and simply echo implode(", ",$articles)
It is better way to do what you want:
<?php
$string = '';
if ($articles) {
foreach($articles as $article) {
$string .= $article->name.", ";
}
}
$string = substr($string, 0, -2);
echo $string;
?>
PHP has a lot of good array functions, and this screams for one of them.
$namesArray = array_map(function($x){return $x->name;}, $articles);
$string = implode(',' $namesArray);
OR
$first = true;
array_walk(function($x) use (&$first)
{
if(!$first) {echo ', ';} else{$first = false;}
echo $x->name;
}, $articles);
I really like the above response with the __toString function also, but I wanted to show these array functions because i think they are often underused in favor or unnecessary foreach loops.
You can remove last comma and space by using trim function. It is the easiest way..
<?php
if ($articles) {
foreach($articles as $article) {
echo trim(implode(", ", $article->name), ', ');
}
}
?>