currently i have some comma seperated values like
"oranges, apples, pies"
and i want to turn those into a list like this
oranges
apples
pies
hope anyone can help me here
$data = "oranges, apples, pies";
$data = explode(',', $data);
echo '<ul>';
foreach ( $data as $item ) {
echo '<li>', trim($item), '</li>';
}
echo '</ul>';
[sarcasm=on]
For those who are looking for unmaintainable, hard-to-read code with no complex stuff like arrays and looping through them (yeah, I know, string technically is a kind of array, though it's different from what usually is meant with arrays):
$input = 'oranges, apples, pies';
$output = '';
$output = '<ul><li>';
$inputLength = strlen($input);
$skipSpaces = true;
for ( $n = 0; $n < $inputLength; ++$n ) {
if ( $skipSpaces ) {
if ( $input[$n] === ' ' ) {
continue;
}
$skipSpaces = false;
}
if ( $input[$n] === ',' ) {
$skipSpaces = true;
$output .= '</li><li>';
continue;
}
$output .= $input[$n];
}
$output .= '</li></ul>';
var_dump($output);
$slist = "oranges, apples, pies";
echo "<ul><li>" . str_replace(", ", "</li><li>", $slist) . "</li></ul>";
Will only add none yet mentioned possibilities:
printf(
'<ul><li>%s</li></ul>',
implode(
'</li><li>',
str_getcsv("oranges, apples, pies")
)
);
though str_getcsv is somewhat overkill if you dont have multiple rows and enclosing chars and stuff like that. Can just as well just use explode then.
Yet another possibility:
echo '<ul>';
$tok = strtok("oranges, apples, pies", ',');
while ($tok !== false) {
echo '<li>', trim($tok), '</li>';
$tok = strtok(',');
}
echo '</ul>';
And another one:
$dom = new DOMDocument;
$dom->appendChild(
$dom->createElement('ul')
);
foreach(explode(',', 'oranges, apples, pies') as $fruit) {
$dom->documentElement->appendChild(
$dom->createElement('li', $fruit)
);
}
$dom->formatOutput = TRUE;
echo $dom->saveXml($dom->documentElement);
And a final one:
$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startElement('ul');
foreach(explode(',', 'oranges, apples, pies') as $fruit) {
$writer->writeElement('li', $fruit);
}
$writer->endElement();
Related
I'm trying to make my list of tags, organized with first letter heads, to show Alphabet (a, b, c, d, etc..) first then numbers and symbols (#,1,2,3 etc..)
here is my code:
<?php $list = '';
$tags = get_tags();
$groups = array();
if( $tags && is_array( $tags ) ) {
foreach ($tags as $tag) {
$first_letter = strtoupper( $firstLetter );
$groups[ $first_letter ][] = $tag;
}
if( !empty( $groups ) ) {
foreach( $groups as $letter => $tags ) {
usort($letter, 'myComparison');
$list .= "\n\t" . '</ul><h2>' . apply_filters( 'the_title', $letter ) .'</h2>';
$list .= "\n\t" . '</ul><ul id="archiveEach">';
foreach( $tags as $tag ) {
$lower = strtolower($tag->name);
$name = str_replace(' ', ' ', $tag->name);
$naam = str_replace(' ', '-', $lower);
$link = $tag->link;
$list .= "\n\t\t" . '<li>'.$name.'</li>';
}}}}else $list .= "\n\t" . '<p>Sorry, but no tags were found</p>';
print_r( $list);
?>
I've tried to sort using different functionalities, using this
function myComparison($a, $b){
if(is_numeric($a) && !is_numeric($b))
return 1;
else if(!is_numeric($a) && is_numeric($b))
return -1;
else
return ($a < $b) ? -1 : 1;
}
then calling the function using usort($differnentelements, 'myComparison')
I cannot get it to work -- any suggestions would be really greatly appreciated. thanks!
PHP to display feed items and list them alphabetically and display first letter of each title above. It is only show one letter above the whole list and it is the letter of the first title on the feed. I changed feedurl here for privacy purposes. Any Ideas?
<?php
$rss = new DOMDocument();
$feed = array();
$urlArray = array(array('url' => 'https://feeds.megaphone.fm/SH')
);
foreach ($urlArray as $url) {
$rss->load($url['url']);
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue
);
array_push($feed, $item);
}
}
usort( $feed, function ( $a, $b ) {
return strcmp($a['title'], $b['title']);
});
$previous = null;
foreach($item as $value) {
$firstLetter = substr($value, 0, 1);
if($previous !== $firstLetter)
$previous = $firstLetter;
}
$limit = 3000;
echo '<p>'.$firstLetter.'</p>';
echo '<ul style="list-style-type: none;>"';
for ($x = 0; $x < $limit; $x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
echo '<li>';
echo ''.$title.'';
echo '</li>';
}
echo '</ul>';
?>
Your foreach loop that determines the first letter of the title is outside the for loop that actually prints it. Therefore, you are always going to output the last letter of the foreach loop.
Move that part inside the for loop, something like
$limit = 3000;
$previous = null;
$count_firstletters = 0;
for ($x = 0; $x < $limit; $x++) {
$firstLetter = substr($feed[$x]['title'], 0, 1); // Getting the first letter from the Title you're going to print
if($previous !== $firstLetter) { // If the first letter is different from the previous one then output the letter and start the UL
if($count_firstletters != 0) {
echo '</ul>'; // Closing the previously open UL only if it's not the first time
}
echo '<p>'.$firstLetter.'</p>';
echo '<ul style="list-style-type: none;>"';
$previous = $firstLetter;
$count_firstletters ++;
}
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
echo '<li>';
echo ''.$title.'';
echo '</li>';
}
echo '</ul>'; // Close the last UL
Is there any way to add an increment value while imploding an array?
This is the piece of code I'd like to have the increment value:
$entries = '<ul class="repeatData"><li class="listEntry1">' . implode('</li><li class="listEntry'. $countme .'">', $data) . '</li></ul>';
I'd like somehow to make the variable $countme increment every time it implodes each array value, if this is even possible.
You cannot do this with implode, but look into applying an anonymous function to the array. You can probably do what you want with not much more code.
$entries = '<ul class="repeatData">';
$countme = 1;
array_walk($data, function ($element) use (&$entries, &$countme) {
$entries .= '<li class="listEntry'. $countme .'">'. $element . '</li>';
$countme++;
});
$entries .= "</ul>";
Explanation: I have written an anonymous function, told it about $entries and $counter (so it is a closure, in fact) so that it can modify them from inside its scope, and passed it to array_walk, which will apply it to all elements of the array.
There is no built in function for that. You have to write your own:
This function generalizes the problem and takes an array of glues and the data as arguments. You may refine it to fit more to your needs...
function custom_implode($glues, $pieces) {
$result = '';
while($piece = array_shift($pieces)) {
$result .= $piece;
$glue = array_shift($glues);
if(!empty($pieces)) {
$result .= $glue;
}
}
return $result;
}
Usage:
$glues = array();
for($i = 0; $i < $end; $i++) {
$glues []= '</li><li class="listEntry'. $i .'">';
}
echo custom_implode($glues, $data);
You can save the for loop which populates $glues if you customize the function a little bit more:
function custom_implode($start, $pieces) {
$result = '';
$counter = $start;
while($piece = array_shift($pieces)) {
$result .= $piece;
if(!empty($pieces)) {
$result .= '</li><li class="listEntry'. $counter .'">';
}
}
return $result;
}
To expand upon #ravloony's answer, you can use a mapping function with a counter to produce what you want, the following function could assist.
function implode_with_counter($glue, $array, $start, $pattern) {
$count = $start;
$str = "";
array_walk($array, function($value) use ($glue, $pattern, &$str, &$count) {
if (empty($str)) {
$str = $value;
} else {
$str = $str . preg_replace('/' . preg_quote($pattern, '/') . '/', $count, $glue) . $value;
$count++;
}
});
return $str;
}
Example use:
echo implode_with_counter(' ([count]) ', range(1,5), 1, '[count]');
// Output: 1 (1) 2 (2) 3 (3) 4 (4) 5
For your case:
$entries = '<ul class="repeatData"><li class="listEntry1">'
. implode_with_counter('</li><li class="listEntry[countme]">', $data, 2, '[countme]')
. '</li></ul>';
Update: Alternative
An alternative approach is to just implement a callback version of implode(), and provide a function. Which is a little more universally usable, than the pattern matching.
function implode_callback($callback, array $array) {
if (!is_callable($callback)) {
throw InvalidArgumentException("Argument 1 must be a callable function.");
}
$str = "";
$cIndex = 0;
foreach ($array as $cKey => $cValue) {
$str .= ($cIndex == 0 ? '' : $callback($cKey, $cValue, $cIndex)) . $cValue;
$cIndex++;
}
return $str;
}
Example use:
echo implode_callback(function($cKey, $cValue, $cIndex) {
return ' (' . $cIndex . ') ';
}, range(1,5));
// Output: 1 (1) 2 (2) 3 (3) 4 (4) 5
Your case:
$entries = '<ul class="repeatData"><li class="listEntry1">'
. implode_callback(function($cKey, $cValue, $cIndex) {
return '</li><li class="listEntry' . ($cIndex + 1) . '">';
}, $data)
. '</li></ul>';
No, implode doesn't work that way.
You will need to create your own function to do that.
You should also consider if this is what you really need. In both Javascript and CSS you can easily reference the n-th child of a node if you need to do that.
I'm using a foreach loop to echo out some values from my database, I need to strip the last comma from the last loop if that makes sense.
My loop is just simple, as below
foreach($results as $result){
echo $result->name.',';
}
Which echos out
result,result,result,result,
I just need to kill that pesky last comma.
Better:
$resultstr = array();
foreach ($results as $result) {
$resultstr[] = $result->name;
}
echo implode(",",$resultstr);
1. Concat to string but add | before
$s = '';
foreach ($results as $result) {
if ($s) $s .= '|';
$s .= $result->name;
}
echo $s;
2. Echo | only if not last item
$s = '';
$n = count($results);
foreach ($results as $i => $result) {
$s .= $result->name;
if (($i+1) != $n) $s .= '|';
}
echo $s;
3. Load to array and then implode
$s = array();
foreach ($results as $result) {
$s[] = $result->name;
}
echo implode('|', $s);
4. Concat to string then cut last | (or rtrim it)
$s = '';
foreach ($results as $result) {
$s .= $result->name . '|';
}
echo substr($s, 0, -1); # or # echo rtrim($s, '|');
5. Concat string using array_map()
echo implode('|', array_map(function($result) { return $result->name; }, $results));
$result_names = '';
foreach($results as $result){
$result_names .= $result->name.',';
}
echo rtrim($result_names, ',');
I've been having the same issue with this similar problem recently. I fixed it by using an increment variable $i, initializing it to 0, then having it increment inside the foreach loop. Within that loop place an if, else, with the echo statement including a comma if the $i counter is less than the sizeof() operator of your array/variable.
I don't know if this would fix your issue per se, but it helped me with mine. I realize this question is years-old, but hopefully this will help someone else. I'm fairly new to PHP so I didn't quite understand a lot of the Answers that were given before me, though they were quite insightful, particularly the implode one.
$i=0;
foreach ($results as $result) {
$i++;
if(sizeof($results) > $i) {
echo $result . ", ";
} else {
echo $result;
}
}
In modern PHP, array_column() will allow you to isolate a column of data within an array of objects.
Code: (Demo)
$results = [
(object)['name' => 'A'],
(object)['name' => 'B'],
(object)['name' => 'C']
];
echo implode(',', array_column($results, 'name'));
Output:
A,B,C
That said, since you are iterating a result set, then you may be better served by calling a CONCAT() function in your sql, so that the values are already joined in the single value result set.
If you are processing a collection in Laravel, you can pluck() and implode():
$collection->pluck('name')->implode(',')
$arraySize = count($results);
for($i=0; $i<$arraySize; $i++)
{
$comma = ($i<$arraySize) ? ", " : "";
echo $results[$i]->name.$comma;
}
Not as pretty, but also works:
$first=true;
foreach($results as $result){
if(!$first) { echo ', '; }
$first=false;
echo $result->name;
}
Another smart way is:
foreach($results as $result){
echo ($passed ? ',' : '') . $result->name;
$passed = true;
}
In this case at first loop $passed is NULL and , doesn't print.
I know this is an old thread, but this came up recently and I thought I'd share my alternate, cleaner way of dealing with it, using next().
$array = array("A thing", "A whatsit", "eighty flange oscillators");
foreach( $array as $value ){
echo $value;
$nxt = next($array);
if($nxt) echo ", "; // commas between each item in the list
else echo ". And that's it."; // no comma after the last item.
}
// outputs:
// A thing, A whatsit, eighty flange oscillators. And that's it.
play with it here
I have to do this alot because I'm always trying to feed numbers in to jplot, I find its easier to put the comma in the front of the loop like so:
foreach($arrayitem as $k){ $string = $string.",".$k;
}
and then chop off the first character (the comma) using substr, it helps if you know a guestimate of long your string will be, I'm not sure what the limit on substr max character is.
echo substr($a,1,10000000);
hope this helps.
$a[0] = 'John Doe';
$a[1] = 'Jason statham';
$a[2] = 'Thomas Anderson';
$size = count($a);
foreach($a as $key=>$name){
$result .= $name;
if($size > $key+1) $result .=', ';
}
echo $result;
<?php
$return = array(any array)
$len = count($return);
$str = '';
$i = 1;
foreach($return as $key=>$value)
{
$str .= '<a href='.$value['cat_url'].'>'.$value['cat_title'].'</a>';
if($len > $i)
{
$str .= ',';
$i = $i+1;
}
}
echo $str;
?>
<?php
$i = 1;
$count = count( $results );
foreach( $results as $result ) {
echo $result->name;
if ( $i < $count ) echo ", ";
++$i;
}
?>
This is what I normally do, add a comma before the item rather than after, while ignoring the first loop.
$i = 0;
$string = '';
foreach($array as $item){
$string .= ($i++ ? ',' : '').$item;
}
First get all the output by using output buffering. Then, trim the comma and display it. So, do it like this:
ob_start();
foreach($results as $result)
{
echo $result->name.',';
}
$output = ob_get_clean();
echo rtrim($output, ',');
The output buffering method helps if the inside loop is very big (and OP is posting here just for brevity), then using OB is easier without changing the internals of the loop.
This might actually be a css question but I'm hoping not because I'd like this to work in IE.
I have the following loop:
<?php
if ($category)
{
foreach($category as $item)
{
echo $item['name'];
echo ", ";
}
} ?>
Which should output
item, item, item, item,
The only thing is...I'd like to NOT have a comma after the last item. Is there any way to do this within a loop?
Well to keep your code how it is, you could add a counter, and skip the last one.
<?php
if ($category) {
$counter = 0;
foreach($category as $item)
{
$counter++;
echo $item['name'];
if ($counter < count($category)) {
echo ", ";
}
}
}
?>
Or you can do it much, much, quicker:
<?php echo implode(", ", array_map(create_function('$item', 'return $item["name"];'), $category)); ?>
Don't echo immediately but save your output into a variable that you can trim.
<?php
if ($category) {
$output = '';
foreach($category as $item) {
$output .= $item['name'];
$output .= ", ";
}
echo rtrim($output, ', ');
}
?>
The implode solution is the simplest, but you asked for a loop. This method avoids putting an extra conditional in the loop, and therefore should be somewhat more efficient. Basically, instead of doing something different for the last item, you do something different for the first item.
$myArray = array(); //Fill with whatever
$result = $myArray[0];
for ($idx = 1; $idx < count($myArray); $idx += 1)
{
$result .= ', ' . $myArray[$idx];
}
EDIT: After realizing you want $item['name'] instead of just $item:
$myArray = array(); //Fill with whatever
$result = $myArray[0]['name'];
for ($idx = 1; $idx < count($myArray); $idx += 1)
{
$result .= ', ' . $myArray[$idx]['name'];
}
As lovely as foreach is,...
<?php
if ($category) {
$count = count($category) - 1;
for ($i = 0; $i <= $count; $i++) {
echo $category[$i]['name'];
if ($i < $count)
echo ', ';
}
}
?>
...for is sometimes necessary.
Assuming $category is an array, you can use implode to get what you want:
Edit: Missed the $categories['name'] part, this should work:
<?php implode(", ", array_keys($category, 'name')); ?>
The standard solution to the "last comma" problem is to put items into an array and then implode it:
$temp = array();
foreach($category as $item)
$temp[] = $item['name'];
echo implode(', ', $temp);
If you want this more generic, you can also write a function that picks ("plucks") a specific field out of each subarray:
function array_pluck($ary, $key) {
$r = array();
foreach($ary as $item)
$r[] = $item[$key];
return $r;
}
and then just
echo implode(', ', array_pluck($category, 'name'));
Or you could check for the last key:
end($category);
$lastkey = key($category);
foreach ( $category AS $key => $item ) {
echo $item['name'];
if ( $lastkey != $key ) {
echo ', ';
}
}
And another option:
<?php
$out = "";
foreach ($category as $item)
{
$out .= $item['name']. ", ";
}
$out = preg_replace("/(.*), $/", "$1", $out);
echo $out;
?>