0

I have an array of IDs, lots of the IDs occur multiple times and I'm using array_count_values() to count how many times each ones occurs.

I want to do something if a specific ID occurs more than 3 times, I just can't figure out how to get the array_count_values() result into a foreach loop so I can use it.

Any help appreciated!

$array = array("297","297","297","297","188","188"); 

print_r( array_count_values($array) );

// loop room booking data
foreach($array as $key => $val) {

    // if the ID occurs more than 3 times
    if ( $val > '3' ) {
        // do something
    }

}
0

2 Answers 2

3

Assign the array_count_value result to a variable and pass this value to foreach loop like below

    <?php 
    $array = array("297","297","297","297","188","188"); 

    $array1 = array_count_values($array); // assign result to array1 variable

    // loop room booking data
    foreach($array1 as $key => $val) {

        // if the ID occurs more than 10 times
        if ( $val > '3' ) {
            // do something
            echo $key; // return value e.g 297
            echo $value; // return no. of times ID occure e.g. 4

        }

    }
    ?>

running Code

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks that works, but how do I echo the ID which occurs more than 3 times in the //do something section? I can only seem to get the value of how many times the ID has occured, but not the actual ID
@TheBobster check my code I have echo $key it will gives you ID
Thanks, not sure how I missed that!
@TheBobster if its working for you please accept this as answer
3

Assign the result of the function to a variable, then loop over that variable.

$frequencies = array_count_values($array);
foreach ($frequencies as $id => $count) {
    if ($count > 3) {
        echo "$id occurs $count times<br>";
    }
}

2 Comments

Thanks that works, but how do I echo the ID which occurs more than 3 times in the //do something section? I can only seem to get the value of how many times the ID has occured, but not the actual ID
$key contains the ID.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.