SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Addict bkennedy's Avatar
    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
    ----------------

  2. #2
    SitePoint Wizard
    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

    cheers

  3. #3
    SitePoint Addict bkennedy's Avatar
    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"); 
    I want this to return the number "3" when I search for the number "2"...
    there are three occurences of "2"...
    how do i do that?
    thx for the help.
    ----------------
    bob.kennedy
    ----------------

  4. #4
    SitePoint Addict bkennedy's Avatar
    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
    ----------------

  5. #5
    SitePoint Wizard
    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
    in function..
    PHP Code:
    function count_arr_str($searchFor$string) {
    $str str_count(in_array($searchFor$string));
    return 
    $str;

    cheers
    Last edited by reminder; Oct 9, 2004 at 04:20.

  6. #6
    SitePoint Addict bkennedy's Avatar
    Join Date
    Aug 2004
    Location
    michigan
    Posts
    251
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks a ton
    ----------------
    bob.kennedy
    ----------------


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •