3
   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

4 Answers 4

2

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';
?>
Sign up to request clarification or add additional context in comments.

Comments

2

Try array_search

$key = array_search('joe', $array);
echo $array[$key];

2 Comments

Awesome, code that works and doesn't. Try finding bill and you'll find that joe is a persistent little blighter.
that's because $key remains empty
0

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

Comments

0

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.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.