Jump to content

Check a value for one key in a multi-dimensional array


haku

Recommended Posts

Lets say I have a multidimensional array:

 

array
(
  array('name'=>'tom', 'age' => 1),
  array('name'=>'dick', 'age' => 2),
  array('name'=>'harry', 'age' => 3),
)

 

is it possible to check to check to see if a certain value exists in 'age', without looping through the main array elements? For example, I want to see any of the people are 3 years old.

 

I've used in_array() lots in the past, but it seems you need to give both keys if you want to check a multi-dimensional array, whereas I only want to check against one key (age).

You could always write a custom foreach statement. I don't think there is a built in one key search. I threw this together for you:

<?php
/* 
-- Params:
-- 	Search item, 
--	Array to search in, 
--	Key to search in, 
--	value to return
*/
function search_key($needle, $haystack, $skey, $rkey) {
foreach($haystack as $k=>$v)
	if(is_array($v) && isset($v[$skey]) && $v[$skey] == $needle)
		if(isset($v[$rkey])) 
			return $v[$rkey];
		else
			return true;
return false;
}

// Setup the array
$array = array
(
array('name'=>'tom', 'age' => 1),
array('name'=>'dick', 'age' => 2),
array('name'=>'harry', 'age' => 3),
);

// See what you have 
echo search_key(2, $array, 'age', 'name');
// prints 'dick'
?>

Thanks mate.

 

I've already got my code looping through the array, I was just wondering if there was a function, or a way of using a function, that could do it already with less code and processing.

 

Not to my knowledge, the shortest code is probably almost the same as what you already have:

 

foreach($arr as $a)
   if($a['age'] == 3)
      echo $a['name'];

 

The only other thing I can think of would be using the array_search() function and passing the returned key to the array, but I think you would still have to have some kind of iteration.  Something like:

 

echo $arr[array_search(3, $arr)];

What about this -

<?php
$e = array(
        array(  'name'  => 'tom',
                'age'   => 1
        ),
        array(  'name'  => 'dick',
                'age'   => 2
        ),
        array(  'name'  => 'harry',
                'age'   => 3
        )
);

function validAge ($val, $key) {
        if ($key === 'age' && $val === 3) echo "woot";
}

$k = array_walk_recursive($e, 'validAge');

It's really essentially the same thing though isn't it - stepping through each element of the array.

I thought it was already stated that you have to. I don't see any other way to go about it. Just that my way, you don't have to write a loop yourself and if you have arrays 3 levels down, it'll still DTRT.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.