PHP - Delete last 2 characters in a loop - php

I have the following which produces results for me.
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
echo $author['fullname'] .', ';
}
It prints it out perfect, except on the last run it still adds the comma and space, is there a way i can strip this from the last result, so its:
name, name, name, name
Instead of the following
name, name, name, name,
Cheers

A better way of doing this would be to separate out the handling of database results from the view/output logic, and then you can sidestep the issue all together, using implode to allow PHP to join each of your authors together into a single string, split by your delimiter of a comma and a space:
// your loop {
$authors[] = $author['fullname'];
}
// your output
echo implode(', ', $authors);

Just concate the data into a string and then remove the last 2 chars using
$author['fullname'] = substr($author['fullname'], 0, -2);
Refer the manual for substr http://php.net/manual/en/function.substr.php

Instead of echoing each author out you could put them in a string and then simply use trim() to take off the trailing comma and finally echo the whole string.

this will probably work
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
//echo $author['fullname'] .', ';
}
$name_count = count($author[]);
for($x=0;$x<$name_count ;$x++){
if($x == $name_count -1){
echo $author['fullname'];
}else{
echo $author['fullname'].", ";
}
}
the idea is to detect the last array index, so that we can apply all the commas after each name except to the last one.

don't ever echo inside foreach
$var = '';
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
$var .= $author['fullname'] .', ';
}
echo trim($var,', ');

Related

Remove last comma from string in while loop

My select query is like this, in group_name i am giving comma but I want to remove comma from last. I already tried with trim but it removes all commas, and I want to remove last comma only.
$selctGroup = "SELECT contact_id,group_name FROM contact_group
LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id`
WHERE contact_id = ".$row['contact_id'];
$selctGroupRes = mysql_query($selctGroup);
while($groupRow = mysql_fetch_array($selctGroupRes))
{
echo $groupRow['group_name'].',';
}
Instead of echoing out each line, build up a string to echo at the end. Before that, remove the lingering comma from the end with rtrim($str,",").
$str = "";
while($groupRow = mysql_fetch_array($selctGroupRes)) {
$str .= $groupRow['group_name'].',';
}
echo rtrim($str,",");
$selctGroup = "SELECT contact_id,group_name FROM contact_group
LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id`
WHERE contact_id = ".$row['contact_id'];
$selctGroupRes = mysql_query($selctGroup);
$str='';
while($groupRow = mysql_fetch_array($selctGroupRes))
{
if($str=='')
$str=$groupRow['group_name'];
else
$str.=','.$groupRow['group_name'];
}
echo $str;
Using rtrim().Like below
rtrim($groupRow['group_name'])
Store your data in array and using implode you can remove last comma
while($groupRow = mysql_fetch_array($selctGroupRes))
{
$result[] = $groupRow['group_name'];
}
echo implode(",", $result);

PHP how to remove last separator?

I have tried a tons of variations, but I can't find the solution. Previously the output was like this:
word a
word b
word c
etc
I have changed some parts of code and now output is:
word a | word b | word c |
How to remove last separator?
The code is:
<div id="right">
<div id="synonyms">
<?
$separator = '<span class="pipe">|</span>';
$sql = mysql_query("SELECT DISTINCT word, id_word FROM words WHERE word LIKE '$word' ORDER BY word ASC LIMIT 100");
echo mysql_error();
while ($row=mysql_fetch_row($sql))
{
$word_synonym = $row[0];
$id_word_synonym = $row[1];
$sql2 = mysql_query("SELECT DISTINCT synonym, id_synonym FROM synonyms WHERE id_word = '$id_word_synonym' ORDER BY synonym ASC");
echo mysql_error();
$num_results =mysql_num_rows($sql2);
while ($row=mysql_fetch_row($sql2))
{
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
echo "".$separator."".$synonym." ";
}
}
?>
</div>
I tried to add $separator = substr($separator, -1, 0); and a lot of other suggestions, but without result.
My preference when doing something like this is to build an array of the strings, then use implode when outputting the final string. This is particularly useful because then I can do other things like merge groups, filter them, etc.
This was posted before and removed, but I think it's worth including as an optional method. Although I prefer Kolink's method, I've used this, too:
Use an iterator ($i) to identify the first (or last) item.
$i=0;
while ($row = mysql_fetch_row($sql2)) {
$i++;
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
echo ($i>1?$separator:"").'$synonym';
}
Not part of this answer, but here's an example of Kolink's (arguably superior) method:
$links=array();
while ($row = mysql_fetch_row($sql2)) {
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
$links[]='$synonym';
}
if (!empty($links)) {
echo implode($separator,$links);
}

Picking numbers in an order

I had a task to slide images from a mysql database using jquery slide and not the animation scripts. The slide is supposed to show at least the most recent ten images that was uploaded. With that I first of all wrote a random query
mysql_query("select * from tblname order by rand() limit 1);
But as expected, it picks the images at random irrespective of when it was posted and of course it wasn't the most recent ten. After some thought I now had to first run a query to get the most recent ten
mysql_query("select * from tblname order by ID limit 10);
while($row=mysql_fetch_array($sql){
$slideid=$slideid.",".$row['recordid'];
}
this of course results to a variable of this order
$var="23,22,24,34,27,78,56,87,98,55";
I tried handling it like an array but it wasn't giving any positive result, hence I had an issue of how to pick this numbers and use it for the slide
$myArr=explode(',',$var);
sort($myArr);
for($i=0;$i<count($myArr);$i++)
{
echo $myArr[$i];
}
Edit: For better efficiency use:
$myArr=explode(',',$var);
sort($myArr);
foreach ($myArr as $val)
{
echo $val;
// Or do whatever else you want with each one.
}
Edit 2: See comments below on efficiency vs for loops vs unexpected results. :)
Based on your comments I will offer my 2p into the mix
this is what I did $slideid="23,22,24,34,27,78,56,87,98,55"; $arr =
explode(',',$slideid); foreach ($arr as $val) { //lets get the
variables from the form post $rs = mysql_query("SELECT * FROM tblname
WHERE id='$val'") or die(mysql_error());
while($row=mysql_fetch_array($rs)){ echo "<img src='image/$image'>"; }
} the images are displayed one by one using jquery slide
Now I think we are wasting time dealing with exploding this variable because mysql has the nifty IN() function (possibly in other db's I don't know)
$slideid = "23,22,24,34,27,78,56,87,98,55";
$rs = mysql_query("SELECT * FROM tblname WHERE id IN({$slideid})") or die(mysql_error());
while ($row = mysql_fetch_assoc($rs))
{
echo "<img src='image/{$row['image']}' />";
}
I hope this helps
$var="23,22,24,34,27,78,56,87,98,55";
$arr = explode(',',$var);
foreach ($arr as $val) {
// work with $val
}
explode splits the string to an array
1) Explode the string into an array, splitting on the comma.
2) You didn't say whether you wanted to re-order the numbers into numerical order, or process them in the order they're already in. If the former, sort the array with sort($arr);
3) Loop over the array in sequence and do something with each number
$str = '1,2,3,4,5,6';
$arr = explode(',', $str);
foreach($arr as $num) echo $num.'<br />';
Note if there is any change of spaces after commas, a better choice would be preg_split rather than explode, as this is more dynamic.
$arr = preg_split('/, ?/', $str);
You can achieve this using php explode function
$pieces = explode(",", $var);
echo $pieces[0]; // piece1
echo $pieces1; // piece2
.
.
.
echo $pieces[n]; // piece n
I think you need to get result of order with respect to order of variable here
$slideid = "23,22,24,34,27,78,56,87,98,55";
$rs = mysql_query("SELECT * FROM tblname WHERE id IN({$slideid}) ORDER BY FIELD(id, {$slideid}) ") or die(mysql_error());
while ($row = mysql_fetch_assoc($rs))
{
echo "<img src='image/{$row['image']}' />";
}

Remove last comma or prevent it from being printed at all MySQL/PHP

I am printing a set of words that is placed in a MySQL database and I am retrieving it with PHP. I want to present it as a comma separated list, but I need it not to print or remove the last comma. How could I do this?
I did try to use rtrim, but I did not probably do it right.
This is my code as it is today:
<?php
$query0 = "SELECT LCASE(ord) FROM `keywords` ORDER BY RAND()";
$result0 = mysql_query($query0);
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keyword = $row0['LCASE(ord)'];
echo "$keyword, ";
?>
I did try to use rtrim, my attempt was something like this (I might be honest enough to say that I am in above my head in this ;) )
$keyword = $row0['LCASE(ord)'];
$keywordc = "$keyword, ";
$keyword- = rtrim($keywordc, ', ');
echo "$keyword-, ";
As you might imagine, this did not print much (but at least it did not leave me with a blank page...)
I would do:
$keywords = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keywords[] = $row0['LCASE(ord)'];
}
echo implode(',', $keywords);
I usually do this by placing the results in an array first
$some_array = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC)) {
$some_array[] = $row0['LCASE(ord)'];
}
then simply:
echo "My List: " . implode(', ', $some_array);
// Output looks something like:
My List: ord1, ord2, ord3, ord4
substr($string, 0, -1);
That removes the last character.

PHP mysql query judge and not echo the repeart part

I want to make a php search query. First, I put a sentence and explode every word get $name,Then I put $name make a query to match all the name which is exist in my database. Then echo part $row['name'][$i] has some word repeat.
for example: the sentence is :Marc Gasol is the brother of Pau Gasol and Gasol in my database, so the match words Gasol apearl 2 times. how to echo $row['name'][$i]; and get only one Gasol? thanks,
$query = mysql_query("SELECT * FROM books WHERE name like '$name[0]' OR name like '$name[1]' OR name like '$name[2]' OR name like '$name[3]' ");
$i = 0;
while($row = mysql_fetch_array($query)) {
echo $row['name'][$i];
$i++;
}
$sentence = "Marc Gasol is the brother of Pau Gasol";
$words = preg_split("/\s+/", $sentence);
//this will uniqueify your value set
$uniqueWords = array_keys(array_flip($words));
foreach($uniqueWords as $word){
$parts[] = "name like '%".mysql_real_escape_string($word)."%'";
}
$where = implode(" OR ", $parts);
$query = mysql_query("SELECT * FROM books WHERE $where ");
$i = 0;
while($row = mysql_fetch_array($query)) {
echo $row['name'][$i];
$i++;
}
You could run another quick loop through your array and remove all duplicate words before you proceed to executing your sql query that way you don't search the name twice in the first place. That should work if I am understanding what you are wanting to do.

Categories