View Full Version : Select data form array that matches condition

11-22-2003, 09:15 PM

I've got a question about selecting data from an array. I've got an array with the following format:

$db[0]['name'] = 'john'
$db[0]['age'] = 18
$db[0]['gender'] = 'm'

$db[1]['name'] = 'janet'
$db[1]['age'] = 17
$db[1]['gender'] = 'f'


I want to select the array keys of the items that match a condition that is constructed as 'gender = m' or 'age > 10'. I want to write a function that can return an array that contains all the keys of the array $db that match the condition.

E.g. if the condition 'gender = m' is used the function should return: $return = array(0)

And if the condition is 'age > 10' the function should return $return = array(0,1)

How would I go about that? What functions should I examine further? Can anyone push me in the right direction?

I hope I've been clear enough ... if not please let me know and I'll elaborate. Thanx in advance for your replies!

Cheers, Michiel

11-22-2003, 09:54 PM
try this, note that for = you should use ==, it makes it easier.

$matches = array();
$condition = 'gender == m';


$condition_parts = explode(" ", $condition);
$condition_parts[2] = (preg_match("/^([0-9]*)$/is", $condition_parts[2]) ? $condition_parts[2] : "\\\\\\"".$condition_parts[2]."\\\\\\"");

eval("if(\\$db[\$i]['".$condition_parts[0]."'] ".$condition_parts[1]." ".$condition_parts[2]."){
array_push(\\$matches, \\$i);



and $matches would be your returned results. This is untested, i will have a test and come back in a minute.

11-23-2003, 02:59 PM
slightly cut down version not using regexp:

function findKeys($array,$field,$value) {
foreach ($array as $key=>$info) {
if ($info[$field] == $value) {
$matches[] = $key;
return $matches;

now you just pass it as a function like so:

$matches = findKeys($db,'name','John');

To find keys of all elements where name == 'John' in the arrray $db.

Also untested but i cant see any obvious mistakes off hand, i'll test it if i get a chance in a minute.



function findKeys($array,$field,$condition,$value) {
foreach ($array as $key=>$info) {
eval('if ($info[$field] '.$condition.' $value) {
$matches[] = $key;
return $matches;

$db[0]['name'] = 'john';
$db[0]['age'] = 18;
$db[0]['gender'] = 'm';

$db[1]['name'] = 'janet';
$db[1]['age'] = 17;
$db[1]['gender'] = 'f';



I re-read you post and noticed the bit about the condition, so i altered my function slightly, this example inputs your sample data and outputs the results, syntax is now

findKeys(<the array>,<field to search>,<condtion>,<value>);

11-23-2003, 03:01 PM
the only trouble with that would come is if you wanted !=, <, >, <= ect.

11-23-2003, 03:08 PM
heh, just fixed that.

11-23-2003, 09:53 PM
Thanx guys!

That has realy helped me a lot! Looks quite simple as well, damn why didn't I figure that out myself ;)

Cheers! Michiel