SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Location
    Limbo
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    finding specific value in ASSOC array

    Hi there,

    I'm having quite a lot of trouble with my script. I'm using in_array() which apparently after research have found out this does not work with associative arrays.

    First let me tell you what I want to accomplish: All I need to do is find a specific 'id' from the associative array, there could be multiples id's but only one with a specific value which I'm searching for.

    Again after doing a few google searches I tried looking for different ways. array_key_exists() was recommended but doesn't that only look for the key so if I look for a specific id = 2 it only looks for id. Or does nit not?

  2. #2
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Location
    Limbo
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just used a loop instead. thanks

  3. #3
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    4,812
    Mentioned
    141 Post(s)
    Tagged
    0 Thread(s)
    Maybe array_search()? If you have a multi-dimension array, it looks like the comments has a solution for that as well.

  4. #4
    SitePoint Member
    Join Date
    Jun 2012
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    this is very unclear. Post your code so that we can understand your question. I think you want to count values, try array_count_values look it up maybe it is what you need.

  5. #5
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Location
    Limbo
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've just decided to go with a loop. My dataset won't be any larger than 0-10 and rarely, rarely over 10. But thanks.

  6. #6
    Resident OCD goofball! bronze trophy Serenarules's Avatar
    Join Date
    Dec 2002
    Posts
    1,911
    Mentioned
    26 Post(s)
    Tagged
    0 Thread(s)
    Two functions you must know when using arrays: array_keys and array_values. When using assoc arrays, you can split the keys and values up into separate non-assoc arrays.

    This should do it.

    PHP Code:
    $values = array(
    'bob' => 'friend',
    'sam' => 'enemy'
    );

    $isEnemyPresent in_array('enemy'array_values($values)); 
    Of course, if the value you are looking for is nested even deeper, it would be wiser to create a recursive method to dig into it.


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
  •