tags:

views:

72

answers:

4
   array(
  [0]
      name => 'joe'
      size => 'large'
  [1] 
      name => 'bill'
      size => 'small'

)

I think i'm being thick, but to get the attributes of an array element if I know the value of one of the keys, I'm first looping through the elements to find the right one.

foreach($array as $item){
   if ($item['name'] == 'joe'){
      #operations on $item
   }
}

I'm aware that this is probably very poor, but I am fairly new and am looking for a way to access this element directly by value. Or do I need the key?

Thanks, Brandon

+1  A: 

Try array_search

$key = array_search('joe', $array);
echo $array[$key];
Sarfraz
Perfect, thank you.
Orbit
@Brandon: You are welcome...
Sarfraz
Awesome, code that works *and* doesn't. Try finding `bill` and you'll find that `joe` is a persistent little blighter.
salathe
A: 

If searching for the exact same array it will work, not it you have other values in it:

<?php
$arr = array(
array('name'=>'joe'),
array('name'=>'bob'));
var_dump(array_search(array('name'=>'bob'),$arr));   
//works: int(1)
$arr = array(
array('name'=>'joe','a'=>'b'),
array('name'=>'bob','c'=>'d'));
var_dump(array_search(array('name'=>'bob'),$arr));   
//fails: bool(false)
?>

If there are other keys, there is no other way then looping as you already do. If you only need to find them by name, and names are unique, consider using them as keys when you create the array:

<?php
$arr = array(
'joe' => array('name'=>'joe','a'=>'b'),
'bob' => array('name'=>'bob','c'=>'d'));
$arr['joe']['a'] = 'bbb';
?>
Wrikken
A: 

If you need to do operations on name, and name is unique within your array, this would be better:

 array(
 'joe'=> 'large',
 'bill'=> 'small'
 );

With multiple attributes:

 array(
 'joe'=>array('size'=>'large', 'age'=>32),
 'bill'=>array('size'=>'small', 'age'=>43)
 );

Though here you might want to consider a more OOP approach.

If you must use a numeric key, look at array_search

Pete
A: 

You can stick to your for loop. There are not big differences between it and other methods – the array has always to be traversed linearly. That said, you can use these functions to find array pairs with a certain value:

  • array_search, if you're there's only one element with that value.
  • array_keys, if there may be more than one.
Artefacto
Ah, this makes me understand a bit better. I'm storing a lot of data in session, so I don't have to query for it each time I need to access it. Is this bad practice?
Orbit