View Full Version : Working With The Results Of explode()

09-01-2006, 03:24 AM
I've used explode() to seperate a string of words into a whole bunch of substrings, and now need to manipulate them a bit beyond merely echoing them out one by one.

Firstly, there will be duplicated substrings, how would I go about removing them?

After removing any duplicates I then need to echo all the remaining substrings as a list on my page, how would I run a while loop on them to do this?

Thanks in advance.

09-01-2006, 04:56 AM
Take a look a array_unique


as for a quick simple display



09-01-2006, 04:57 AM
Check out array_unique() (http://us3.php.net/manual/en/function.array-unique.php)

Loop your array:
count() (http://us2.php.net/count)
for loop (http://us2.php.net/manual/en/control-structures.for.php)

ref: http://us2.php.net/manual/en/language.control-structures.php

Good luck;

09-01-2006, 10:15 PM
Thank you.

Okay, I've taken my best stab at this now - how am I doing? :D Seriously, I'm a little stuck with the for loop and would appreciate some help.

Firstly, the data is a string of words seperated by spaces. Processing the array looks like this:

$taglist = mysql_query ("SELECT tags FROM bookmarks");
$tags1 = explode (" ", $taglist);
$tags = array_unique ($tags1);
$numtags = count ($tags);

That seems simple enough so far. Now the for loop:

for ($numtags; $numtags > 0; $numtags--) {
echo $tags[0];

Firstly, I'm assuming using $numtags as the initial value is the right thing to do here, given that I aim to echo each substring individually, correct?

Secondly, is "$numtags--" the right way to decrement?

Thirdly, how do I increment the array number in each iteration of the loop?


09-01-2006, 10:23 PM

for($i = 0; $i < $numtags; $i++)
echo $tags[$i] . "<br>";

09-01-2006, 10:46 PM
Ah, the joys of lateral thinking. Thanks Brandoe :thumbsup:

EDIT: A further problem has arisen.

The current code is echoing out the following:

Resource id #2

I've read enough to establish that there is a problem in that I'm not converting the data in to a usable form. My gut instinct is that mysql_fetch_array needs to be incorporated somewhere but I'm not sure how or where.

$taglist = mysql_query ("SELECT tags FROM bookmarks") or die(mysql_error());
$tags = array_unique (explode (" ", $taglist));
$numtags = count ($tags);

for($i = 0; $i < $numtags; $i++)
echo $tags[$i] . "<br>";

I've checked that I'm connected to the database, there is no problem there.