Trying to count occurences of uknown array elements

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
primate
Forum Commoner
Posts: 49
Joined: Fri Jun 18, 2004 4:38 am
Location: England, UK

Trying to count occurences of uknown array elements

Post by primate »

Hi

I'm writing a scrip to crunch through the Syslogs stored in an MS SQL database from various PIX's in my organisation.

For a particular part of the script I have retrieved all the data I need (FWIW source IP's of connection attempts), formatted and stripped extraneous stuff and got them sitting in an indexed array. Now I'm stuck.

What I am trying to do is run through the array and at each occurence of a new IP address do something with it (I won't know what the IP addresses are at this stage) which will let me count the number of times each IP address is found, then order the output by the most frequently occuring IP address. hmm....

I'm really stuck, new to php in general and this is my first attempt at doing something useful with it so any help appreciated.
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

[php_man]array_count_values[/php_man]() should solve all your problems.
primate
Forum Commoner
Posts: 49
Joined: Fri Jun 18, 2004 4:38 am
Location: England, UK

Post by primate »

duh, I'd read that earlier but completely missed the point of it :oops:

Thanks, I'll try it out now!
User avatar
Wayne
Forum Contributor
Posts: 339
Joined: Wed Jun 05, 2002 10:59 am

Post by Wayne »

maybe try

Code: Select all

$array_count = array_count_values($your_array); // your array, is the array containing all the ip's
sort($array_count);
reset($array_count);
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

I think array_count_values sorts itself, highest first.

Code: Select all

<?php

//assuming the IP array is called '$ip';

print_r(array_count_values($ip)); 

?>
Should do the trick.
primate
Forum Commoner
Posts: 49
Joined: Fri Jun 18, 2004 4:38 am
Location: England, UK

Post by primate »

I ended up using:

Code: Select all

<?php

$sortedips = array_count_values($sourceips);
natsort($sortedips);
$rsortedips = array_reverse ($sortedips);
reset ($sortedips);

?>
array_count_values() made the key the IP address with the element the number of connection attempts.

I used natsort() to sort by the elements then array_reverse () 'd it so the highest no. of connection attempts was at the top.

Is there a better way?
Post Reply