1

I have an array like the following in PHP:

$my_array = array();
$my_array[] = array("id"=>"myid1", "name"=>"myname1");
$my_array[] = array("id"=>"otherid", "name"=>"othername");
$my_array[] = array("id"=>"morestuffid", "name"=>"morestuffname");

Having a "name" like "othername", is it possible to retrieve the respective "id" from $my_array without a for loop?

9
  • array_walk() maybe array_map()? Commented May 9, 2016 at 3:56
  • do you want to retrieve the id only for othername or for the respective ids for all the names in the array? Commented May 9, 2016 at 4:00
  • do you have reasons to avoid using foreach? Commented May 9, 2016 at 4:03
  • I want to retrieve the id for the respective name. Note: There are no repeated elements. Commented May 9, 2016 at 4:05
  • @kekit, you can do that using foreach and break. So why do you want to avoid using the loop? Commented May 9, 2016 at 4:06

2 Answers 2

7

you can get your array column name by array_column method.Then find you want string by array_search its will return the index of array.

$index = array_search("othername",array_column($my_array,"name"));
var_dump($my_array[$index]["id"]);
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you. Much more elegant than a for loop. That's what I was looking for. Kudos.
@kekit, I doubt you'll find it elegant when you'll look at your code after a couple of months. This code is also inefficient, as takes at least 2 loops.
@kekit, also, array_column generates an extra array
Maybe you're right. However, I tested both approaches and checked the time in miliseconds, in php7 and the results are really similar, something like 1,...xE^-5 ... sometimes a method is faster, sometimes it is the other, but found no hegemony or significant difference. I'm always open to brainstorming... :)
You saved my life!
0

Please use

$id = array_filter( 
        array_map(
            function($array) {
                if($array['name']== 'othername'){
                    return $array['id']; 
                }
            },$my_array
        )
    ); 
print "<pre>";print_r($id);

Comments

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.