PHP loop, change last item? - php

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;
?>

Related

create div from each item in tags column

My tags column is like this:
first row: sky - earth - sea
second row: iron - silver - gold
third row: apple - fruit - food
...and so on
Want to create a div from each item, like this:
<div class='tagdown'>sky</div>
<div class='tagdown'>earth</div>
$st = $db->query("select tags from posts");
$arr = array();
$items = "";
while ($row = $st->fetch()) {
array_push($arr, explode(' - ', $row['tags']));
}
foreach($arr as $item) {
$items .= "<div class='tagdown'>" . $item . "</div>\n";
}
echo $items;
Notice: Array to string conversion...
Another Try:
for ($i = 0; $i < count($arr); ++$i) {
$items .= "<div class='tagdown'>" . $arr[$i] . "</div>\n";
}
echo $items;
Notice: Array to string conversion...
Any help?
Dont push and again traverse your array. just print out data in while loop. Try following code:
$items = "";
while ($row = $st->fetch()) {
$arr = explode(' - ', $row['tags']);
$items .= "<div class='tagdown'>".implode("</div>\n<div class='tagdown'>",$arr)."</div>\n";
}
echo $items;
Try like shown below
Example :
<?php
$items = "";
$str = "sky-earth-sea";
$arr = explode("-", $str);
$count = count($arr);
for($i = 0; $i < $count; $i++) {
$items .= "<div class='tagdown'>".$arr[$i]."</div></br>";
}
echo $items;
?>
explode() returns an array and you are pushing an array into an other array
its making 1 2D array you can check thar using print_r($arr);
use this
while ($row = $st->fetch()) {
$tag=explode('-', $row['tags'];
foreach($tag as $t){
array_push($arr,$t ));
}
}
You can also use fetch associative if using mysqli_connect
while ($row = $result->fetch_assoc()) {
array_push($arr, explode(' - ', $row['tags']));
}
foreach($arr as $a) {
foreach($a as $v){
$items .= "<div class='tagdown'>" . $v . "</div>\n";
}
}
echo $items;
-------------- OR -------------
$arr = array();
$items = "";
while ($row = $result->fetch_assoc()) {
$tag = explode(' - ', $row['tags']);
foreach($tag as $v){
$items .= "<div class='tagdown'>" . $v . "</div>\n";
}
}
echo $items;

Set all my foreach loop data into one variable like $results

I have a simple foreach like the following:
$range = range(1, 10);
foreach ($range as $times) {
echo 'example' . $times . '<br>';
}
what would output the result below-
example1
example2
example3
example4
example5
example6
example7
example8
example9
example10
instead of having the echo 'example' . $times . '<br>';
i would like to echo one variable and have the same result, any answers welcome.
You mean build a string?
$results = '';
foreach(range(1, 10) as $i) {
$results .= "example${i}\n";
}
If you don't want to make an array, you can do something like:
$results = '';
$range = range(1, 10);
foreach ($range as $times) {
$results .= "example".$times."<br />";
}
echo $results;

How to remove "," in foreach()?

I have a code php
foreach ($cities as $city) {
echo substr($city->name . ", ", 0, -2);
}
result is: a, b, c, d, e,
How to remove "," in foreach()
Exactly: a, b, c, d, e
You could achieve the same with less code, by using the implode function.
$comma_separated = implode(',', $cities);
Should give you exactly what you want.
$str = '';
foreach ($cities as $city){
$str .= "$city, ";
}
$str = rtrim($str, " ,");
In this context you can not remove the last comma without additional tags.
You have two other options:
1. Use the standard for loop:
for ($i=0; $i < count($cities)-1; $i++) {
echo $cities[$i]->name . ", ";
}
echo $cities(count($cities)-1)->name;
2. Create a result string in the foreach, remove the last character and than print it.
Just do :-
echo implode(',', $cites);
That will give you your desired output.
I just noticed from your code that $cities is an object not an array, sorry:-
foreach($cities as $city){
$cityNames[] = $city->name;
}
echo implode(',', $cityNames);
http://www.php.net/implode
$first = true;
foreach ($cities as $city) {
if( !$first ){
echo ', ';
}else{
$first = false;
}
echo $city->name;
}
Change it a bit to something like:
$first = TRUE;
foreach ( $cities as $city )
{
if ( !$first )
{
echo( "," );
}
$first = FALSE;
echo( $city->name );
}
Use rtrim after the foreach():
$city->name = rtrim($city->name,',');
Method 1 :
$index = 0;
foreach ($cities as $city) {
$index++;
echo $city->name . ($index == count($cities)?"":",");
}
Method 2:
$str = "";
foreach ($cities as $city) {
$str .= $city->name . ",";
}
$str = substr_replace($str ,"",-1);
echo $str;

Create a comma-separated string from a single column of an array of objects

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.

Getting results from a PHP array: How can I wrap every 5 results in Unordered List?

I have an array containing a "Variable" amount of results/entries.
I use foreach as normal to echo the array results.
Problem: I want to wrap every 5 results from the array in Unordered list.
I do not know the total number of results since it's variable. So for example if it contains 18 items. It should display 4 ULs, the first 3 ULs containing 5 results and the last UL contains only the remaining 3 items.
Is that simple to do? Thanks very much in advance for your help. :)
I rarely used this function, but array_chunk seems to do what you want.
$chunks = array_chunk($original, 5);
foreach ($chunks as $each_chunk) {
// echo out as unordered list
}
This is a fairly straightforward algorithm:
$htmlOutput = "";
for($i=0;$i<count($myArray);$i++)
{
if($i%5==0)
{
$htmlOutput.= "<ul>";
}
$htmlOutput.= "<li>".$myArray[$i]."</li>";
if($i%5==4)
{
$htmlOutput.= "</ul>";
}
}
if(count($myArray)%5!=0)
{
$htmlOutput.= "</ul>";
}
echo $htmlOutput;
You may need to modify this a bit to suit your requirements
$cnt = 1;
foreach ($arr as $key => $val)
{
if($cnt==1) echo "<ul>";
echo "<li>$val</li>";
$cnt++;
if($cnt==5)
{
echo "</ul>";
$cnt=1;
}
}
How about this:
<?php
$num_per_list = 5; // change me
$dudes = array("bill","jim","steve","bob","jason","brian","dave","joe","jeff","scott");
$count = 0;
$list_items = "";
foreach($dudes as $dude) {
$break = (($count%$num_per_list) == ($num_per_list-1));
$list_items .= "<li>" . $dude . "</li>";
if(($break) || (count($dudes)==($count+1))) {
$output = "<ul>" . $list_items . "</ul>";
$list_items = "";
// Output html
echo $output;
}
$count++;
}
?>
Let's suppose you put the list in an array...
$count = 0;
foreach ($unorderedList as $item) {
$count = ($count + 1)%5;
if ($count == 0) {
// wrap here
}
...do the stuff for every item you need
}

Categories