2

I think that from the title it's not entirely clear, but this is the situation:

I have an array like this one (it's bigger, this is just an example):

$array = array(
    array('name' => 'John', 'age' => '29', 'from' => 'Uknown'),
    array('name' => 'Brad', 'age' => '27', 'from' => 'Idk'),
    array('name' => 'Phil', 'age' => '31', 'from' => 'My House')
);

I'm trying to find a fast-way using native functions of PHP (without using loops or other things) that specifing the name of this array inside another array, it gives me back the info related to this name.

Example:

If I specific Brad it gives me back an array with:

array('name' => 'Brad', 'age' => '27', 'from' => 'Idk')
LF00
  • 27,015
  • 29
  • 156
  • 295
Keaire
  • 879
  • 1
  • 11
  • 30
  • i don't think you can do that without checking the name field. even if there's a native function for this, it'll be using loops under the hood – mehulmpt Apr 27 '17 at 12:47
  • You're right, I wasn't very clear in the message. I meant without using loops and do a new function when there's an approach cleanier and easier using native functions of PHP. – Keaire Apr 27 '17 at 13:19

3 Answers3

2

This is my approach

$key = array_search('Brad', array_column($array, 'name'));

print_r($array[$key]);

For reference
PHP docs : array-search
PHP docs : array-column

VikingCode
  • 1,022
  • 1
  • 7
  • 20
1

Suppose your don't have duplicate item and duplicate name.

$names = array_column($array, 'name');
$indexs = array_flip($names);
print_r($array[$indexs['Brad']]);
LF00
  • 27,015
  • 29
  • 156
  • 295
0

There's no such functions. The only option you have is to rebuild your array as:

$array = array(
    'John' => array('name' => 'John', 'age' => '29', 'from' => 'Uknown'),
    'Brad' => array('name' => 'Brad', 'age' => '27', 'from' => 'Idk'),
    'Phil' => array('name' => 'Phil', 'age' => '31', 'from' => 'My House')
);

And use simple isset:

if (isset($array['Brad'])) {
    print_r($array['Brad']);
} else {
    echo 'Brad not found';
}

And of course if name values repeat in your array, you have to create more unique keys.

u_mulder
  • 54,101
  • 5
  • 48
  • 64