Remove the last part of the comma in foreach in PHP? - 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);

Related

PHP: create string with values separated by comma BUT without comma at the end of string

I am using the following PHP snippet to echo data to an HTML page.
This works fine so far and returns results like the following example:
value1, value2, value3, value4, value5,
How can I prevent it from also adding a comma at the end of the string while keeping the commas between the single values ?
My PHP:
<?php foreach ($files->tags->fileTag as $tag) { echo $tag . ", "; } ?>
Many thanks in advance for any help with this, Tim.
If
$files->tags->fileTag
is an array, then you can use
$str = implode(', ', $files->tags->fileTag);
implode(", ", $files->tags->fileTag);
A simple way to do this is keep a counter and check for every record the index compared with the total item tags.
<?php
$total = count($files->tags->fileTag);
foreach ($files->tags->fileTag as $index => $tag) {
if($index != $total - 1){
echo $tag.',';
} else{
echo $tag;
}
?>
<?php
echo implode(",",$files->tag->fileTag);
?>
Assuming you're using an array to iterate through, how about instead of using a foreach loop, you use a regular for loop and put an if statement at the end to check if it's reached the length of the loop and echo $tag on it's own?
Pseudocode off the top of my head:
for($i = 0, $i < $files.length, $i++){
if ($i < $files.length){
echo $tag . ", ";
} else {
echo $tag;
}
}
Hope that helps x
Edit: The implode answers defo seem better than this, I'd probably go for those x

How do I get rid of comma after last array item?

I have this array loop:
foreach ( $event_entrance as $event_entrance_s ) {
_e($event_entrance_s,'holidayge');
echo ', ';
}
I'd like to ger rid of comma at the end of the last loop.
Any ideas? Seems simple, but it isn't for me :)
$fn = function($v) { return _e($v,'holidayge'); };
$arr = array_map($fn, $event_entrance );
echo implode(',', $arr);
Two options:
use implode to put things together, it handles this edge case for you easily. Seriously, implode is great
determine if you're on the last element (perhaps with a count, and by accessing the element key) and omit the comma if it's the last element.
What about...
$limit = count($event_entrance);
foreach ($event_entrance as $key => $event_entrance_s) {
_e($event_entrance_s,'holidayge');
if ($key < ($limit-1)) {
echo ', ';
}
}
As long as your keys are integers and sequential, this should work exactly as you intend. If you're using integers, but they are not in any particular order, putting this before your foreach() loop will fix that:
$event_entrance = array_values($event_entrance);
If you are using strings as keys instead of integers, try something like this:
$limit = count($event_entrance);
$i = 1;
foreach ($event_entrance as $event_entrance_s) {
_e($event_entrance_s,'holidayge');
if ($i < $limit) {
echo ', ';
}
++$i;
}
Try something like this:
$event_entrance_count = count($event_entrance);
$loop_number = 1;
foreach ( $event_entrance as $event_entrance_s ) {
_e($event_entrance_s,'holidayge');
if(!$loop_number == $event_entrance_count) {
echo ', ';
}
$loop_number++;
}

PHP Add comma to every item but last one

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

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'], ", ");

Input PHP Variable into HTML Select Tag

I have a php variable ($list) that is a list of values separated by commas. I am trying to figure out how to convert or input this variable into a HTML select tag. Here is what I have so far:
$dbquery = #$db->query('SELECT * FROM Company');
while ($queryText = $dbquery->fetchArray()){
$array[]=$queryText['Company_Name'];
}
//the next batch of code, which is not included, converts the $array[] into a variable named $list//
//the values for $list are: Company1, Company2, Company3, Company4...//
//HTML select tag//
echo '<select name="testSelect" id="testId">';
echo '<option value="'.$list.'">'.$list;
echo '</option></select>';
I understand that I would need a loop like a "while" or a "for" to list the values within $list, but I am not sure of the exact syntax. Can anyone assist me with this?
Thanks,
DFM
You'll need an option element for every list item (company name).
<select name="testSelect" id="testId">
<?php foreach ($array as $companyName): ?>
<option value="<?php echo $companyName; ?>"><?php echo $companyName; ?></option>
<?php endforeach; ?>
</select>
You need to explode() the list into an array (if you can't use $array directly for some reason) then do:
$listArray = explode(', ', $list);
echo '<select name="testSelect" id="testId">';
foreach ($listArray as $item)
echo '<option value="'.htmlspecialchars($item).'">'. htmlspecialchars($item) . "</option>\n";
echo '</select>';
Why are you converting the array into a comma separated list in the first place? Once you have an array you can do
foreach ($company in $list) {
echo '<option value="' . htmlspecialchars($company) . '">' . htmlspecialchars($company) . '</option>';
}
to output your options. If you for some reason really need to have the comma separated list step, you can always use explode(',', $list) to convert it back to an array.
You could use something like explode() to put the list of stuff into an array, then loop through that.. something like:
$myArray = explode(",", $list);
echo "<select name=\"testSelect\" id=\"testId\">\n";
for($i = 0; $i < count($myArray); $i++) {
// add each option to select list..
echo "<option>" . $myArray[$i] . "</option>\n";
}
echo "</option>\n";
More on PHP explode() function:
http://www.php.net/manual/en/function.explode.php
See implode()
You can simulate the implode() function with a loop and string concatenation.
For example:
$out = '';
$append = ', ';
for($arr as $v)
{
$out .= $v.$append;
}
$out = substr($out, 0, (-1) * strlen($append));

Categories