Forum Moderators: coopster
- John
<?php
$text = "trout trout trout lucky";
$pieces = explode(" ",$text);$count = array();
foreach ($pieces as $key => &$value)
{
if (!in_array($value,$count))
{
$count[$value]='1';
}
else
{
$value++;
}
}
?>
2.) You're using in_array() rather than a str function, and by using foreach() which is basically comparing array pieces, you are switching from an array comparison to a string comparison.
I don't like foreach(), because all the benchmarking I've read says it's about inefficient, but if I was doing it with a foreach() I would do it like this:
<?php
$text = "trout trout trout lucky";
$pieces = explode(" ",$text);
$count=array();
$string='';
foreach ($pieces as $piece)
{
if (strstr($string,$piece))
{
$count[$piece]++;
}
else
{
$string.=" ".$piece;
$count[$piece]=1;
}
}
print_r($count);
?>