views:

166

answers:

3

I have an array as follows

array(2) {
  ["operator"] => array(2) {
    ["qty"] => int(2)
    ["id"] => int(251)
  }
  ["accessory209"] => array(2) {
    ["qty"] => int(1)
    ["id"] => int(209)
  }
  ["accessory211"] => array(2) {
    ["qty"] => int(1)
    ["id"] => int(211)
  }
}

I'm trying to find a way to verify an id value exists within the array and return bool. I'm trying to figure out a quick way that doesn't require creating a loop. Using the in_array function did not work, and I also read that it is quite slow.

In the php manual someone recommended using flip_array() and then isset(), but I can't get it to work for a 2-d array.

doing something like

if($array['accessory']['id'] == 211)

would also work for me, but I need to match all keys containing accessory -- not sure how to do that

Anyways, I'm spinning in circles, and could use some help. This seems like it should be easy. Thanks.

+1  A: 

Hey dardub, you can use array_walk to verify if a particular value is within your array - array_walk iterates through al elements of you array and applys a provided function to them, so basically you would need to create that function. It is used as follows:

$arr = array(
    'one' => array('id' => 1),
    'two' => array('id' => 2),
    'three' => array('id' => 3)
);

function checkValue($value, $key)
{
    echo $value['id'];
}

array_walk($arr, 'checkValue');

You'll just need to add to your function whatever conditionals/validations you'd need.

Hope it helps.

M.

EDIT: PHP docs on array_walk http://www.php.net/manual/en/function.array-walk.php

falomir
You should add a link to the documentation and also mention that you can pass a third parameter to `array_walk` which again will be passed to the callback function (i.e. this is the way to pass the `id` to search for).
Felix Kling
can I have the function return a bool? I'm having trouble getting that part to work?
dardub
array_walk returns true or false but depending on whether the callback was successfully executed or not - you can use a a flag (a global variable) to indicate whether the value you are looking for was found or not.
falomir
Thanks for the help falomir and Felix. I think I can get this working to suit my needs.
dardub
A: 

This function is useful in_array(211, $array['accessory']); It verifies the whole specified array to see if your value exists in there and returns true.

in_array

Jonathan Czitkovics
A: 
$map = array();
foreach ($arr as $v) {
    $map[$v['id']] = 1;
}
//then you can just do this as when needed
$exists = isset($map[211]);

Or if you need the data associated with it

$map = array();
foreach ($arr as $k => $v) {
    $map[$v['id']][$k] = $v;
}
print_r($map[211]);
chris