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/>';
}
Related
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);
The code below is a simple version of what I am trying to do. The code will read in two files, see if there is a matching entry and, if there is, display the difference in the numbers for that item. But it isn't working. The first echo displays the word but the second echo is never reached. Would someone please explain what I am missing?
$mainArry = array('Albert,8');
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
if (in_array($kword[0], $mainArry)) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
Your $mainArry contains a single element: the string 'Albert,8'. It looks like you want to use it as an array (elements 'Albert' and '8') instead of a string.
You mention the code will read from two files, so you can 'explode' it to a real array, as you do with $arry. A simpler approach would be using str_getcsv() to parse the CSV string into $mainArry.
$inputString = 'Albert,8';
$mainArry = str_getcsv($inputString); // now $mainArry is ['Albert','8']
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
if (in_array($kword[0], $mainArry)) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
Test it here.
You are attempting to compare the string Albert with Albert,8, so they won't match. If you want to check if the string contains the keyword, assuming your array has more than one element, you could use:
$mainArry = array('Albert,8');
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
foreach ($mainArry as $comp) {
if (strstr($comp, $kword[0])) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
}
example: https://eval.in/728566
I don't recommend your way of working, but this is a solution, basically the process you apply to the $arry should also apply to the $mainArry you're trying to compare it to.
$mainArry = array('Albert,8');
$arry = array('Albert,12');
/***
NEW function below takes the valus out of the main array.
and sets them in their own array so they can be properly compared.
***/
foreach ($mainArry as $arrr){
$ma = explode(",",$arrr);
$names[] = $ma[0];
$values[] = $ma[1];
}
unset($arrr,$ma);
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
/// note var reference here is updated.
if (in_array($kword[0], $names)) {
echo '<br>line '.$kword[0]. ' has count of '.$kword[1] . '<br>';
}
}
Yeah, MarcM's answer above does the same thing in a neat single line, but I wanted to illustrate a little more under the hood operations of the value setting. :-/
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
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
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'], ", ");