SitePoint Sponsor |
|
User Tag List
Results 1 to 6 of 6
-
Oct 8, 2004, 13:10 #1
- Join Date
- Aug 2004
- Location
- michigan
- Posts
- 251
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
count occurences of string in array?
How do I count the occurences of a string within an array?
ex: I want to see how many of the elements exactly match the given string.
I've tried
substr_count
but that apparently only works for strings. Any ideas?
Thanks.----------------
bob.kennedy
----------------
-
Oct 8, 2004, 13:15 #2
- Join Date
- Mar 2004
- Posts
- 1,647
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
PHP Code:$string = array("1", "2", "3"); //and so on
$count = count($string);
for(reset($i); $i < $count; ++$i) {
echo $i; /echos number 3
}
-
Oct 8, 2004, 13:30 #3
- Join Date
- Aug 2004
- Location
- michigan
- Posts
- 251
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
so, where do i tell it what i'm searching for?
PHP Code:$string = array("1", "2", "2", "3", "2");
there are three occurences of "2"...
how do i do that?
thx for the help.----------------
bob.kennedy
----------------
-
Oct 8, 2004, 13:36 #4
- Join Date
- Aug 2004
- Location
- michigan
- Posts
- 251
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
I think I got it...
PHP Code:$count = 0;
foreach ($array as $a)
{
if ($a == $searchforthis)
{
$count++;
}
}
echo $count;
----------------
bob.kennedy
----------------
-
Oct 8, 2004, 13:40 #5
- Join Date
- Mar 2004
- Posts
- 1,647
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
PHP Code:$searchFor = "2";
$string = array("1", "2", "2", "3", "2");
$str = str_count(in_array($searchFor, $string));
echo $str;
PHP Code:function count_arr_str($searchFor, $string) {
$str = str_count(in_array($searchFor, $string));
return $str;
}
Last edited by reminder; Oct 9, 2004 at 04:20.
-
Oct 8, 2004, 13:42 #6
- Join Date
- Aug 2004
- Location
- michigan
- Posts
- 251
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
thanks a ton
----------------
bob.kennedy
----------------
Bookmarks