Get rid of last comma [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Removing last comma in PHP?
Remove the last Comma from a string (PHP / Wordpress)
I have code which from some reason is not working. What I am trying to do is get rid of last comma from the result but it won't work. Here is the code
<?php do {
$activity_user_first_name = $row_product_activity['user_first_name'];
$activity_user_last_name = $row_product_activity['user_last_name'];
$name = ''.$activity_user_first_name.' '.$activity_user_last_name.', ';
echo rtrim($name, ",");
} while($row_product_activity = mysql_fetch_assoc($product_activity)) ?> like this
So the results I want to get is this
Steve Jobs, Bill Gates, Sergey Brin, Larry Page like this
instead I get this
Steve Jobs, Bill Gates, Sergey Brin, Larry Page, like this
so I want that comma after Larry Page or any other name that is at the end be deleted. I tried playing around with many other options but the nothing came up as I wish. Any suggestions would be appreciated.

I think a better solution is to construct the string without the trailing comma in the first place. Put the links for each name into an array slot and then just echo some imploded results.
<?php
$names=array();
do {
$activity_user_first_name = $row_product_activity['user_first_name'];
$activity_user_last_name = $row_product_activity['user_last_name'];
$names[] = ''.$activity_user_first_name.' '.$activity_user_last_name.'';
} while($row_product_activity = mysql_fetch_assoc($product_activity));
echo implode(', ', $names);
?> Like This

Related

Show names separated (Getting names from database)

In my database I have one column named name and in each row of that column I'm saving names like this /Mary/Sam/Bob/Michael/. To show the values in my page I need to separate them by breaking the line in each /. Can someone help me?
If I make one echo of my column I will get /Mary/Sam/Bob/Michael/ but I want:
Mary
Sam
Bob
Michael
$names=explode('/', $dbrow['name']);
foreach($names as $aname){
echo $aname.'<br>';
}
Use the explode function with array_filter function
$database_column_string = "/Mary/Sam/Bob/Michael/";
$names = array_filter(explode('/',trim($database_column_string )));
foreach($names as $name){
echo $name;
echo "<br/>";
}
\n may not render a new line in the web browser. So it's better to replace \ with the br tag:
str_replace ("/" , "<br>" , "/Mary/Sam/Bob/Michael/");
The explode function will fix your problem but you should be aware that the way you're using your database is violating the first normal form. Each record should have the same number of attributes.
Here is a guide to the normal forms http://www.bkent.net/Doc/simple5.htm
You should redesign your database to have a table called, for example, Names(id, name)

escape spaces in id attributes or deleting them in php section

i get different string (like a, b, hospital, schools, jobs to work etc. ) as $divname from my db in my PHP section. i use this values as id in mydiv elemnents.
<div id="'.$divname.'"></div>
there is no problem for $divname = a, b, hospital or school but when it comes to jobs to work there is a huge problem cause my id gets spaces and it returns an error to me.
<div id="jobs to work"></div> //as evryone state spaces in id variable is an error.
now my question i need use this $divame variables in my id attribute. how can i do this? how can i delete those spaces or any more idea for using those in id attributes are welcome.
You may do two things:
Use a hashing function to create new id, which will be unqiue as long as your ids are unique as:
$newdivid = md5($olddivid);
You may write a function to remove spaces and combine such string items
function remove_spaces($str) {
$str_arr = explode(' ', $str);
$newstr = "";
foreach($str_arr as $sitem){
$newstr .= trim($sitem);
}
return $newstr;
}
Hope this solves your problem.
i found a php command in another Sof question for this purpose
$new_divname = str_replace(' ', '', $divname);
it deletes all spaces.. and of course my question gets a dublicate:

Additional elements to URLS?

I'm not sure what the terminology is, but basically I have a site that uses the "tag-it" system, currently you can click on the tags and it takes the user to
topics.php?tags=example
My question is what sort of scripting or coding would be required to be able to add additional links?
topics.php?tags=example&tags=example2
or
topics.php?tags=example+example2
Here is the code in how my site is linked to tags.
header("Location: topics.php?tags={$t}");
or
<?php echo strtolower($fetch_name->tags);?>
Thanks for any hints or tips.
You cannot really pass tags two times as a GET parameter although you can pass it as an array
topics.php?tags[]=example&tags[]=example2
Assuming this is what you want try
$string = "topics.php?";
foreach($tags as $t)
{
$string .= "tag[]=$t&";
}
$string = substr($string, 0, -1);
We iterate through the array concatenating value to our $string. The last line removes an extra & symbol that will appear after the last iteration
There is also another option that looks a bit more dirty but might be better depending on your needs
$string = "topics.php?tag[]=" . implode($tags, "&tag[]=");
Note Just make sure the tags array is not empty
topics.php?tags=example&tags=example2
will break in the back end;
you have to assign the data to one variable:
topics.php?tags=example+example2
looks good you can access it in the back end explode it by the + sign:
//toplics.php
<?php
...
$tags = urlencode($_GET['tags']);
$tags_arr = explode('+', $tags); // array of all tags
$current_tags = ""; //make this accessible in the view;
if($tags){
$current_tags = $tags ."+";
}
//show your data
?>
Edit:
you can create the fron-end tags:
<a href="topics.php?tags=<?php echo $current_tags ;?>horror">
horror
</a>

PHP create option list from delimited string without duplicating values

I have a string with values (which are suburbs) like so:
$suburbs = "Mawson, Elizabeth, Burnside, Elizbeth, Mawson";
There COULD be double ups in the suburbs that the string contains. I can't change this fact.
What I am trying to do is create an option list for a drop down menu that a user will use. I do not want to display the same suburb twice( or more for that matter).
What I have so far:
$suburbs = "Mawson, Elizabeth, Burnside, Elizbeth, Mawson";
//Explode the suburbs string delimited by a comma
$boom = explode(',', $suburbs);
foreach($boom as $b)
{
$suburbOptionList .= '<option value='.$b.'>'.$b.'</option>';
}
?>
<select> <?php
echo $suburbOptionList;
?>
</select>
I know that this will simply display all of the options but I really don't know how to display each suburb only once. Ive tried a few foreach,and if combinations but they look ugly and work just as bad.
Any help would be appreciated.
Cheers in advance!
Pass $boom through array_unique() and you'll be fine.
$bada_boom = array_unique($boom);
P.S.: This will not help if you have typos or variations in duplicates. (Elizbeth != Elizabeth).
In that case you will need to get creative.
Also, hw (in comments) made a good point about trimming whitespaces. If the suburbs come from an untrusted source and are improperly formatted, you may need to normalize them. This means trimming whitespaces and normalizing capitals:
$boom = array_walk($boom, 'trim');
$boom = array_walk($boom, 'strtolower');
$bada_boom = array_unique($boom);

active users script, user count not working properly

i have written a script to output active users on my site....
part of this is counting unique ips in the log, as the array i use to split the lines / data unloads active users from the array list after 5 minutes.....
however the "3 online users now" count is not working properly.....
it kinda works.... when someone views a page, it says there is 1 user
lets say i view a page.... 1 visitor
then user 2 views a page .... 2 visitors
but if i then view another page, it displays 3 users.....
even though i use the same ip for both page requests....
here is my code
$data = file_get_contents('active-log.txt');
$break = "\r\n";
$lines = explode($break, $data);
foreach ($lines as $key => $value) {
$active_ip[] = $lines[$key][1];
}
$active_ip_count = array_unique($active_ip);
$active_users = (count($active_ip_count));
$active_users is the variable i use to display how many unique visitors are online at one time
thanks in advance for anyone that can help me thanks
....
EDIT
.....
here is a sample of the log saved....
1328469393|157.55.39.84|g-book
1328469398|157.55.39.84|downloads
1328469400|157.55.39.84|badger
1328469404|157.55.39.84|home
1328469408|157.55.39.84|boneyard-dogs
the first part is timestamp (to remove the line from array, if timestamp is older than 5 minutes... this works fine)
the second part is ip
third part is page viewed and the new line is created with \r\n
$lines[$key][1] is the variable for each ip in each line....
as im not exacly a php expert, when writing scripts, i test them heavily while developing, and each time i add a new line of script , i echo the data, to check its what i hope, to make sure i make no mistakes......
here is a section of code that i didnt paste as i didnt think it was necessary....
foreach($lines as $k=>$v) {
$lines[$k] = explode("|", $v); }
// echo $lines[0][0]; // now this is first array of first line .... line 2 / url would be - $lines[1][2]
this is in my code, straight after the line "$lines = explode($break, $data);" in my code
Have you looked at the output of var_dump($active_ip) after the foreach loop ends? With this setup, I'm pretty sure $lines[$key][1] is simply the first character of the line you're dealing with, so that's not going to work well for a number of reasons. What does active-log.txt look like? Does it only contain IP addresses or user names, too? If it only contains IP addresses, consider using something like this:
<?php
$data = file('active-log.txt');
$no_duplicate_ips = array_unique($data);
$active_users = (count($no_duplicate_ips));
?>
Edit:
Right, that makes sense then. Try this:
$data = file_get_contents('active-log.txt');
$break = "\r\n"; //Note that it's generally a good idea to use PHP_EOL throughout your code, for greater cross-platform compatibility
$lines = explode($break, $data);
$exploded_data = array();
$active_ips = array();
foreach($lines as $v) {
$exploded_data = explode("|", $v);
//Now check whether the timestamp is not > 5 min
if(TIMESTAMP CHECK HERE) {
//OK, this one is not too old
$active_ips[] = $exploded_data[1];
}
}
$active_ip_count = array_unique($active_ip);
$active_users = (count($active_ip_count));

Categories