PHP Add comma to every item but last one - php

I have a loop like
foreach ($_GET as $name => $value) {
echo "$value\n";
}
And I want to add a comma in between each item so it ends up like this.
var1, var2, var3
Since I am using foreach I have no way to tell what iteration number I am on.
How could I do that?

Just build your output with your foreach and then implode that array and output the result :
$out = array();
foreach ($_GET as $name => $value) {
array_push($out, "$name: $value");
}
echo implode(', ', $out);

Like this:
$total = count($_GET);
$i=0;
foreach ($_GET as $name => $value) {
$i++;
echo "$name: $value";
if ($i != $total) echo', ';
}
Explained: you find the total count of all values by count(). When running the foreach() loop, you count the iterations. Inside the loop you tell it to echo ', ' when the iteration isn't last (isn't equal to total count of all values).

$comma_separated = implode(", ", $_GET);
echo $comma_separated;
you can use implode and achieve that

You could also do it this way:
$output = '';
foreach ($_GET as $name => $value) {
$output = $output."$name: $value, ";
}
$output = substr($output, 0, -2);
Which just makes one huge string that you can output. Different methods for different styles, really.

Sorry I did not state my question properly.
The awnser that worked for me is
implode(', ', $_GET);
Thanks, giodamelio

I'd typically do something like this (pseudo code):
myVar
for... {
myVar = i + ","
}
myVar = trimOffLastCharacter(myVar)
echo myVar

Related

Remove the last part of the comma in foreach in PHP?

How can I prevent the insertion of a comma at the end of the title3?
foreach ($_POST['titles'] AS $title) {
echo "{$title},";
};
Result:
title1,title2,title3,
Update :
It comes as a form data, this is array. Don't come this way; title1,title2,title3,
<form>
<select name="titles[]">
<option>title1</title>
<option>title2</title>
<option>title3</title>
<option>title4</title>
</select>
</form>
just use implode() - which is the equivalent to .join():
echo implode(',', $_POST['titles']);
or simply:
echo implode($_POST['titles']);
if you really want to use a loop - an index is required in order to determine the last one element. a foreach loop does not provide any index to compare to; that's why a for loop is rather suitable:
// $titles = explode(',', $_POST['titles']);
$titles = $_POST['titles'];
for($i=0; $i < sizeof($titles); $i++) {
echo $titles[$i];
if($i+1 != sizeof($titles)){echo ',';}
}
looks like you could skip the foreach altogether and just do this:
echo implode(',',$_POST['titles']);
You should use implode instead.
$string = implode(',', $_POST['titles']);
I agree with the other answers - implode() is the way to go. But if you'd rather not/keep on the path you're on...
$output = "";
foreach ($_POST['titles'] AS $title) {
$output .= "{$title},";
};
echo substr($output, 0, -1);

make the data into an array and get the values

I have the data in my table like this
Arabic,Assamese,Azerbaijani,Belarusian
I want to show the data in an array so that I can use foreach and get the values for the array. So can someone tell me how to make it as an array and get values?
$string = "Arabic,Assamese,Azerbaijani,Belarusian";
$language_array= explode(',',$string);
Supposing you have perform the query to the database and already has the data you can use explode function. See this DEMO.
$data = $row['data_from_table']; //your data is Arabic,Assamese,Azerbaijani,Belarusian
$exp = explode(",", $data);
foreach ($exp as $value){
echo $value;
echo PHP_EOL;
}
?>
Use explode function
$database_value = $db['your_data'];
$value_array = explode(',',$database_value);
print_r($value_array);
foreach ($value_array as $value){
echo $value.'<br>';
}

Php foreach - separating each loop with comma except the last element

Heres what i mean:
foreach ($array as $a) {
echo $a.',<br/>';
}
current output would be:
a,
a,
a,
a,
i want the output to be like this:
a,
a,
a,
a
(all 'a' separated with comma and when it comes to the last loop it doesnt write a comma)
Try this:
echo implode(",<br/>", $array);
If the length of array is too large or you have multidimensional array use the below code
<?php $len=count($array);
foreach($array as $a){
echo $a;
if( $len > 1) echo ',';
$len--;
} ?>
If you'd also like to convert any newlines in the array to <br />, which might be ideal if you're outputting:
echo nl2br(implode(',' . PHP_EOL, $array));
PHP has the implode function for that:
implode(",<br>", $array);
Nobody said you can make it this way:
foreach($array as $element) {
$separator = ($element != end($array)) ? ",<br />" : '';
// or $separator = ($element == end($array)) ? '' : ",<br />";
echo $element.$separator;
}
I suppose this is going to output exactly what you wish.
You should use implode except for one situation.
If the output is huge, and you don't want to keep it in memory before sending to the output (e.g. itemwise processing) then you should do something like:
$remain=count($array);
foreach ($array as $a) {
echo $a;
if($remain-->0) echo ',';
echo '<br/>';
}

PHP array does not sort at all

I have a problem with sorting of an array.
$infoGroup is the result of a 'ldap_get_entries' call earlier. As I step through this array I put the result in the array $names.
Then I want to sort $names in alfabetical order, I have tried a number of different methods but to no avail. The array always stays in the same order it was constructed.
What have I missed?
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
unset($names);
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
}
$ai = 0;
This is the result however I try to sort the $names array:
Henrik Lindbom
Klaus Rödel
Admin
Bernd Brandstetter
proxyuser
Patrik Löfström
Andreas Galic
Martin Stalder
Hmmm.. a bit hard to explain, but the issue is because you are sorting your array inside that foreach() loop. Essentially, since you are creating the array element in the iteration of the first loop, the natsort() only has 1 element to sort and your nested foreach() loop is only outputting that 1 element, which is then unset() at the second and further iterations...
Extract that second foreach() that sorts and outputs and remove the unset() from the top of the first loop. This should output your desired results.
Something like this...
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
$ai = 0;

Foreach loop, but for first key do something else

Sorry if this is confusing. It's tough for me to put into words having beginner knowledge of PHP.
I'm using the following foreach loop:
foreach ($_POST['technologies'] as $technologies){
echo ", " . $technologies;
}
Which produces:
, First, Second, Third
What I want:
First, Second, Third
All I need is for the loop to skip the echo ", " for the first key. How can I accomplish that?
You can pull out the indices of each array item using => and not print a comma for the first item:
foreach ($_POST['technologies'] as $i => $technologies) {
if ($i > 0) {
echo ", ";
}
echo $technologies;
}
Or, even easier, you can use implode($glue, $pieces), which "returns a string containing a string representation of all the array elements in the same order, with the glue string between each element":
echo implode(", ", $_POST['technologies']);
For general case of doing something in every but first iteration of foreach loop:
$first = true;
foreach ($_POST['technologies'] as $technologies){
if(!$first) {
echo ", ";
} else {
$first = false;
}
echo $technologies;
}
but implode() is best way to deal with this specific problem of yours:
echo implode(", ", $_POST['technologies']);
You need some kind of a flag:
$i = 1;
foreach ($_POST['technologies'] as $technologies){
if($i > 1){
echo ", " . $technologies;
} else {
echo $technologies;
}
$i++;
}
Adding an answer that deals with all types of arrays using whatever the first key of the array is:
# get the first key in array using the current iteration of array_keys (a.k.a first)
$firstKey = current(array_keys($array));
foreach ($array as $key => $value)
{
# if current $key !== $firstKey, prepend the ,
echo ($key !== $firstKey ? ', ' : ''). $value;
}
demo
Why don't you simply use PHP builtin function implode() to do this more easily and with less code?
Like this:
<?php
$a = ["first","second","third"];
echo implode($a, ", ");
So as per your case, simply do this:
echo implode($_POST['technologies'], ", ");

Categories