I have this little code here :
$arrayName = array('0','1','2');
foreach ($arrayName as $key) {
echo $key . ',';
}
So now the Output is this :
0,1,2,
If i want to have this what should i do ? :
0,1,2
I mean not inserting "," for last object in an array .
thanks .
You can either use join or implode
echo join(',', $arrayName);
OR
echo implode(',', $arrayName);
Do this way:
echo join(',', $arrayName);
You should not use loop with this (i.e. place this instead of loop, not inside loop)
Try to implode them like
$arrayName = array('0','1','2');
echo implode(',',$arrayName);
Related
Some assistance would be greatly appreciated:
The 'foreach' section works perfectly and echo's the result set perfectly; as soon as I try the implode it fails? Thank you!
$ctr = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$RespondentsResultSetArray[$ctr] = array(
"Firstname" => $row['cnt_firstname'],
"Lastname" => $row['cnt_lastname']
);
$ctr = $ctr + 1;
}
foreach ($RespondentsResultSetArray as $key) {
echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
}
sqlsrv_free_stmt($stmt);
echo implode(', ',array_values($RespondentsResultSetArray));
try this
implode(',',$RespondentsResultSetArray);
You are passing an array of arrays to implode function. Here is a little deviation of your code, that should get you to the same result:
$full_array = array();
foreach ($RespondentsResultSetArray as $key) {
echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
array_push($full_array,$key["Firstname"]);
array_push($full_array,$key["Lastname"]);
}
echo implode(', ',$full_array);
Also, for the future, try to chose smaller names for your variables, and use lowercase for your variable names and array index.
The php implode function accepts an array of strings.
You are not passing it an array of strings.
To user1844933 that just answered, your suggestion would pass implode an array of arrays. That won't work for the same reason.
$RespondentsResultSetArray=array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
array_push($RespondentsResultSetArray,$row['cnt_firstname'].' '.$row['cnt_lastname']);
}
$saved_to_variable=implode(', '$RespondentsResultSetArray);
Will create an array of strings which you can then implode
Since you recently commented that you want to save it to a variable rather than echo it, I just changed the last line of the example code. I believe that will give you the properly spaced, and delimited string that you desire.
since$RespondentsResultSetArray is multidimensional array use foreach loop before echo
$string = "";
foreach($RespondentsResultSetArray as $values)
{
echo implode(array_values($values),",");
$string= $string.",".implode(array_values($values),",");
}
$string=ltrim($string,",");
echo $string;
Demo
Hello Guys i need to do this,
I have a common loop
foreach ($stuffs as $stuff) {
echo $stuff;
}
Lets assume $stuff is an 'id' of a mysql table what i have and i dont want to be showed in next results, so i want to build a string like this
1,23,54,67 (comma separated)
So that string will be in mysql query to exclude results that already have been shown.
how can i do that?
Should be with implode? How can i achieve that?
implode should be the tool:
implode(",", $stuffs);
will return a comma separated list.
Test
$myarray=array(1,2,"hello",4,5);
echo implode(",", $myarray);
returns
1,2,hello,4,5
If you really wanna have the loop:
$values = "";
foreach ($stuffs as $stuff) {
$values != "" && $values .= ",";
$values .= $stuff;
}
echo $values;
I suggest using implode, but the loop can really give you more power if you wanna do some further stuff.
This worked in my case (detects if isn't the loop last iteration):
foreach($array as $key => $val){
...
if($key!==count($array)-1){echo ',';}
}
Should be as simple as:
$string = implode(",",$stuffs);
echo $string
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/>';
}
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'], ", ");