Jump to content

[SOLVED] [need assistance] Count number of same value in string


andyhajime

Recommended Posts

Hey guys, I need some assistance in how to do this. Been drowning myself with coffee the whole night with no success. I've read the str_word_count, explode, count_chars and it still doesn't ring any bell. Hope you guys, the experts, can shed some light into this.

 

I have this string:

$code = "big, spiders, funny, scary, big, ugly, giant, mother, big, spiders, babies, hatch, eggs, big, creepy, big, spiders, garage, funny, sequel";

 

If you look at the value, you notice that there's 5 big, 3 spiders, 2 funny, while the rest is only 1 of each.

 

I've been trying to echo out the quantity of each word inside $code like this:

"big" has 5
"spider" has 3
"funny" has 2
"scary" has 1
"ugly" has 1
"giant" has 1
ect....

 

...and not repeating the same word which already stated earlier like this.

 

"big" has 5
"spider" has 3
"funny" has 2
"scary" has 1
"big" has 5 <--- REPEATED
"ugly" has 1
"giant" has 1
ect....

 

Appreciate the help guys......  :shy:

 

Well, I would do this

 

$Str = split($code, ",");
$New = array();

foreach($Str as $v)
{
$v = str_replace(' ', '', $v)
if(isset($New[$v]))
	{
	$New[$v] ++;
	}
else
	{
	$New[$v] = 1;
	}
}

foreach($New as $k=>$v)
{
echo "\"$k\" has $v<br>";
}

Thanks bro  :D.

I did test it out and it echoed this:

"," has 1

 

I made some adjustment and trimming which is now fully workable, though not sure if it's advisable.

 

 

Here's the codes for share if anyone has the same issue as me.

$Str = explode(", ",$code);
$New = array();

foreach($Str as $v)
{
$New[$v] ++;
}

foreach($New as $k=>$v)
{
   echo "\"$k\" has $v<br>";
}

 

 

...and again, thanks Garethp. If you're in Singapore right now, I would definitely give you a treat. I finally can head off to bed but can't sleep. Drowsy with caffeine.  ;D

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.