Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access array element by value

Tags:

php

   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

like image 899
Brandon Frohbieter Avatar asked Feb 28 '26 10:02

Brandon Frohbieter


2 Answers

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';
?>
like image 155
Wrikken Avatar answered Mar 02 '26 00:03

Wrikken


Try array_search

$key = array_search('joe', $array);
echo $array[$key];
like image 37
Sarfraz Avatar answered Mar 01 '26 22:03

Sarfraz