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
Related
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 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);
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
totally stumped in this, basically I'm getting a comma seperated list from a user table, using it as an array and then using each value in the array to fetch data from a different table and output then.
$award_array = array($user_class->awards);
foreach($award_array as $award) {
$getaward = mysql_query("SELECT `name`, `text`, `image` FROM `awards_av` WHERE `id` = '".$award."'");
$awardstuff = mysql_fetch_array($getaward);
echo "<img src='".$awardstuff['image']."' alt='".$awardstuff['name']."' title='".$awardstuff['text']."' />";
}
This is only giving out the first number in the array ($user_class->awards in this case is 1,2,3,4,5,6)
Any help is much appreciated!
I think I see the problem. You cannot simply take a string of a comma separated list, and throw it inside an array() tag and expect it to automatically convert it to an array. You must use the explode() function to do that.
What you're trying to do:
<?php
$string = 'a,b,c,d,e';
$myarray = array($string);
foreach ($myarray as $k => $v) {
print $v .'<br />';
}
?>
Except that doesn't work. You need to convert the comma-separated list of values (which is a string) into an array, but you don't use array() to do that. You use PHP's built-in function called explode() -> http://php.net/explode like this...
<?php
$string = 'a,b,c,d,e';
$myarray = explode(',' $string);
foreach ($myarray as $k => $v) {
print $v .'<br />';
}
?>
I think that is the problem you're having
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'], ", ");