Page 1 of 1

Loop through variable and separate into unique variables

Posted: Thu Aug 26, 2010 9:17 am
by defroster
Hello,

If I have this string:

$tags="baseball glove face" (this can vary from 1 to 15 different words)

how would i loop through and divide these into different

$tag1=baseball
$tag2=glove
$tag3=face
.. and so on (if more words)

Thanks for help

Re: Loop through variable and separate into unique variables

Posted: Thu Aug 26, 2010 9:28 am
by shawngoldw

Code: Select all

$arr = explode(' ', $tags);
This will result in:

Code: Select all

$arr[0] = "baseball"
$arr[1] = "glove" 
etc

Shawn

Re: Loop through variable and separate into unique variables

Posted: Thu Aug 26, 2010 9:33 am
by defroster
Thanks, that is great. How could I write the code so if there were 12 words(tags) it would loop through only 12 times?

Re: Loop through variable and separate into unique variables

Posted: Thu Aug 26, 2010 9:41 am
by shawngoldw
Well it will do it for however many words are in the senetence. If there are 12 it will only make $arr[0], $arr[1], ... $arr[11].
Are you trying to limit it to 12?


Shawn

Re: Loop through variable and separate into unique variables

Posted: Thu Aug 26, 2010 9:56 am
by defroster
Thanks for help, no I would like to loop as many times as there are words.

Re: Loop through variable and separate into unique variables

Posted: Thu Aug 26, 2010 10:34 am
by AbraCadaver
Alternate:

Code: Select all

$tags = "baseball glove face";
$tag  = str_word_count($tags, 1);

Re: Loop through variable and separate into unique variables

Posted: Thu Aug 26, 2010 10:35 am
by defroster
I figured it out. Thanks for help.

Code: Select all

$tags=$row['tags'];
$arraytags = str_word_count($tags, 1);
while (list(, $value) = each($arraytags)) {
echo "<a href='search.php?q=".$value."'>".$value."</a> ";
}

Re: Loop through variable and separate into unique variables

Posted: Thu Aug 26, 2010 10:41 am
by AbraCadaver
Didn't know you wanted to know how to loop. This is shorter:

Code: Select all

$tags = $row['tags'];
foreach(str_word_count($tags, 1) as $value) {
   echo '<a href="search.php?q="'.$value.'">'.$value.'</a>';
}

Re: Loop through variable and separate into unique variables

Posted: Thu Aug 26, 2010 11:08 am
by defroster
Thanks, great stuff :)