Skip to content

Instantly share code, notes, and snippets.

@seantunwin
Last active August 20, 2018 20:29
Show Gist options
  • Select an option

  • Save seantunwin/a0fd1bca92657fed1dbbdb2bdf19bc96 to your computer and use it in GitHub Desktop.

Select an option

Save seantunwin/a0fd1bca92657fed1dbbdb2bdf19bc96 to your computer and use it in GitHub Desktop.
PHP: Search multi-dimensional array for specific key value and return another key's value from the same sub-array
<?php
// Multi-dimensional Array to search through
$a = [
[
'item' => 1,
'code' => 100
],
[
'item' => 2,
'code' => 200
],
[
'item' => 3,
'code' => 300
],
[
'item' => 4,
'code' => 400
]
];
// Array to pass for our search parameters
$search = [
// Key to search for with value as needle
'item' => 3
];
// Target key we want the value for
$targetKey = 'code';
// Get the target value via built-in PHP Array functions
// with a Closure and binding with use()
$targetValue = array_column(array_filter($a, function($x) use ($search) {
if ($x[key($search)] === $search[key($search)]) {
return $x;
}
}), $targetKey)[0];
echo $targetValue; // 300
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment