Searching a PHP array was not as simple as I had thought. Sure, you can use array_search()
but that only finds one value off an array the last time I tried it out. I needed something to search a multidimensional array, for example… I tried many things before I finally figured it out!
Searching a PHP array with array_filter()
I was fooling around with an Online Users script in PHP recently. Since I was determined to get it all done using just a text file, I needed to get my arrays, well, all in an array! 😛
Sample array data from the Online Users script
Here is a sample of the data my Online Users PHP script collected in an array:
<?php // Filename: online.php // Some dummy data in the main multidimensional array // $users['ip']=array( // 'ts'=>[int timestamp], // 'ctr'=>[int counter], // 'pg'=>[str viewing page] ); $users['161.142.1.10'] = array( 'ts'=>1052649255, 'ctr'=>1, 'pg'=>'/forum/' ); $users['202.188.1.5'] = array( 'ts'=>1052649289, 'ctr'=>2, 'pg'=>'/webdsn/' ); $users['192.101.10.55'] = array( 'ts'=>1052649300, 'ctr'=>1, 'pg'=>'/arrays/filter.html' ); $users['65.101.111.58'] = array( 'ts'=>1052649899, 'ctr'=>2, 'pg'=>'/' );
So, according to this data, there are 4 users online; each user being tracked by their IP address, of course. Now every time somebody views a page, this data/array is updated. As well as adding a new IP address to the array, I need to compare the Unix timestamp now with the values already in the array, and remove any user that has ‘timed out’! This is where I needed to use array_filter()
.
Let’s say the Unix time now is 1052649900; so our constant below, TIMED_OUT, would hold the value 1052649300, which means 10 minutes ago i.e. 1052649900-600.
// TIMED_OUT constant set to Unix time 10 minutes ago define( 'TIMED_OUT', time() - 10*60 );
Sample callback function for array_filter()
array array_filter ( array $input [, callable $callback = "" ] )
The PHP array_filter()
function requires two parameters, the array to search i.e. $users (array from example above) and a callback function that we shall now create. We’ll name this callback function update_users()
:
function update_users( $users ) { // compare each $users['ts'] value with the constant // TIMED_OUT and return only those that have // an equal or higher value. return ( $users['ts'] >= TIMED_OUT ); }
Getting the results from a search with array_filter()
Next we create a ‘new’ array, $users_still_online, by using the callback function we created above, like this:
$users_still_online = array_filter( $users, 'update_users' ); // Print the results... print_r( $users_still_online );
Ouput:
Array ( [192.101.10.55] => Array ( [ts] => 1052649300 [ctr] => 1 [pg] => /arrays/filter.html ) [65.101.111.58] => Array ( [ts] => 1052649899 [ctr] => 2 [pg] => / ) )
Meaning that only 2 users were online in the last 10 minutes!