SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Zealot DaisyChain's Avatar
    Join Date
    Aug 2002
    Location
    Manchester, England
    Posts
    149
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Count number of times value occurs in array

    I'm sure there must be a simple answer to this but I just can't find anything. I want to count how many times the variable $var occurs in an array and then return the key for each.

    I'm completely stuck!!

  2. #2
    SitePoint Guru MikeBigg's Avatar
    Join Date
    Jun 2004
    Location
    Reading, UK
    Posts
    970
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry - I misread your post and posted complete nonsense as a result.

    Mike
    Last edited by MikeBigg; Nov 22, 2006 at 07:38.

  3. #3
    SitePoint Guru
    Join Date
    Jul 2005
    Location
    Orlando
    Posts
    634
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    http://www.php.net/manual/en/functio...unt-values.php

    PHP Code:
    <?php

    $my_array 
    = array( 1232);

    $counts array_count_values$my_array );

    echo 
    $counts[2]; // produces 3
    echo $counts[3]; // produces 1;

    ?>

  4. #4
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yet another
    PHP Code:
    $my_array = array( 1232);

    $result preg_grep('/2/'$my_array );

    print_r($result); 

  5. #5
    SitePoint Zealot DaisyChain's Avatar
    Join Date
    Aug 2002
    Location
    Manchester, England
    Posts
    149
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    array_count_values .... I KNEW there had to be something like that!!

    Thanks everyone for your help

  6. #6
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Only Stereofrogs' returns the key and values as you requested: ..and then return the key for each.
    PHP Code:
    Array
    (
        [
    1] => 2
        
    [3] => 2
        
    [4] => 2



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
  •