Skip to content
Advertisement

Remove item by its value from array inside a loop

Given this working code:

$input_array = array(
    "192.168.1.100",
    "192.168.1.101",
    "192.168.1.100",
    "192.168.1.102",
    "192.168.1.103",
    "192.168.1.198",
    "192.168.1.101",
    "192.168.1.25",
    "192.168.1.109",
    "192.168.1.109",
    "192.168.1.109",
    "192.168.1.100",
    "192.168.1.58"
);

$final_array = array();

foreach ($input_array as $value) {
    //if the value is present more or eq 3 times
    if (count(array_keys($input_array, $value)) >= 3) {

        //Add it to final array
        $final_array[] = $value;

        //Echo in the console
        echo "IP $value  will be banned!" . PHP_EOL;

        //Clean up the input array
        foreach ($input_array as $k => $v) {
            if ($value == $v) {
                unset($input_array[$k]);
            }
        }
    }
} 

How would you optimize the “Clean up the input array” phase? Is there a way to delete all the items in the input array those matches the if condition?

Thanks everyone

Advertisement

Answer

Yes, add a key to the initial foreach and use it to unset the value in the input array you are adding to the ban list.

$input_array = array( "192.168.1.100", "192.168.1.101", "192.168.1.100", 
                        "192.168.1.102", "192.168.1.103", "192.168.1.198", 
                        "192.168.1.101", "192.168.1.25", "192.168.1.109", 
                        "192.168.1.109", "192.168.1.109", "192.168.1.100", 
                        "192.168.1.58") ;

$final_array = array();

$counted = array_count_values($input_array);
arsort($counted);   //get the big numbers first
foreach( $counted as $ip=>$cnt ){
    if ( $cnt >= 3 ) {
        $final_array[] = $ip;
        echo "IP $ip  will be banned!" . PHP_EOL;
    } else {
        break;  // stop unnecessary loops once we processed all the >= 3's
    }
}
//tidy the input array
$input_array = array_values(array_diff($input_array,$final_array));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement