Jump to content

Removing the last ' & ' or any 'string' in a concatenation?


KitCarl

Recommended Posts

I'm trying to generate a list of the names of associations from the choices made via check boxes which use the ID ($assoc) to pass a value.

The code below returns the names and as expected adds a ' & ' too each, but I would like to code it to not add the last ' & '.

Did a search on this board and scanned my 'PHP Visual Quickstart Guide' but found nothing to my understanding.

I'm just getting starting with PHP and am not sure this is even close to the best type of code to do this or if an entirely different method is preferred. Any help appreciated and an explanation is always a plus.

 

<?php  $sql = "Select A.a As name
FROM A
WHERE A.aID IN($assoc)";
$result = mysql_query("$sql"); for( $i = 0; $i < $row = mysql_fetch_array($result); $i++)
echo $row["name"]. ' & '; ?>

Link to comment
Share on other sites

by the way, that for loop doesn't make any sense.

for( $i = 0; $i < $row = mysql_fetch_array($result);
//specifically
//$i < $row = mysql_fetch_array($result)

 

this will technically work because of the way that PHP treats comparisons between different types, but probably does not work the way you think it does.

 

What actually happens is that $row is usually an array, and when you compare an array and an integer, an array is always greater. However, when mysql_fetch_array returns false (or some value that casts to false), which will than make the condition false, and exit the loop. perhaps you meant this

for( ; $row = mysql_fetch_array($result) ; )
//or more commonly
while($row = mysql_fetch_array($result))

 

Note: your loop probably "works", but just letting you know it may work in an unintended way.

 

and the way your code is now, you don't actually have a string to use trim on because you just echo the results of the query, without storing them

$str = "";//create empty string
while( $row = mysql_fetch_array($result))
$str .= $row["name"]. ' & '; //concatenate values

$str = trim($str, ' & ');
echo $str;

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.