Access array element by value

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

)

I think I'm fat, but to get the attributes of an array element, if I know the value of one of the keys, I first iterate over the elements to find the right one.

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

I know this is probably very bad, but I'm pretty new and looking for a way to access this element directly by value. Or do I need a key?

Thanks Brandon

+3
source share
4 answers

If you are looking for the same array, it will work, and not you have other values:

<?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 than a loop, as you already do. If you need to find them only by name, and the names are unique, consider using them as keys when creating an array:

<?php
$arr = array(
'joe' => array('name'=>'joe','a'=>'b'),
'bob' => array('name'=>'bob','c'=>'d'));
$arr['joe']['a'] = 'bbb';
?>
+2
source

Try array_search

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

, , :

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

:

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

.

, array_search

0

You can stick with the for loop. There are no big differences between it and other methods - the array should always run linearly. However, you can use these functions to search for pairs of pairs with a specific value:

0
source

Source: https://habr.com/ru/post/1750545/


All Articles