Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Romain's avatar
Level 30

How to get the key based on values?

Hey,

say that I have this:

$array = [
	'english' => [
		'USA',
		'Canada',
		'Australia'
	],
	'spanish': [
		'Spain',
		'Venezuela'
	]
];

How can I simply, using collect() or Arr::, get english from USA?

Thanks

0 likes
11 replies
tykus's avatar
collect($array)->mapWithKeys(
  fn ($item, $key) => collect($item)->mapWithKeys(
    fn ($element) => [$element => $key]
  )
)->get('USA')

This could probably be improved, but works so long as a country is not listed under more than one language ¯\_(ツ)_/¯

2 likes
Romain's avatar
Level 30

Thanks for that, it's an interesting approach.

Could there be another way of going about it from the beginning? Maybe my array is wrong. The point is that I want to have a "top value" (english) for multiple "lower values" (countries). But the array will grow overtime, so I can set it in stone.

aurawindsurfing's avatar

As @tykus pointed out you have it nested so you have to "double" the method to get to the nested level.

abhijeet9920's avatar

@romain

$array  = [
	'english'  => [
		'USA',
		'Canada',
		'Australia'
	],
	'spanish'=> [
		'Spain',
		'Venezuela'
	]
];

return  collect($array)->filter(function($value, $key){
	if(in_array('USA',  $value)){
		return  true;
	}
	return  false;
})->keys();

It may not be the best but it works. Use Collection filter

Romain's avatar
Level 30

Thanks for your reply, you have the same as @corvs but his is a one liner and that would be my preference, so I will make his the best answer.

1 like
CorvS's avatar
CorvS
Best Answer
Level 27

@romain Is it possible that a country exists for multiple keys?

$langKey = collect($array)->filter(fn($lang) => in_array('USA', $lang))->keys()->first();
CorvS's avatar

@romain Then you can add ->first() at the end to get only the single key.

Romain's avatar
Level 30

Yep I'll do that. Just tested and it works as expected. I'll set your first reply as the best answer, please add ->first() in it.

Thanks again

1 like

Please or to participate in this conversation.