5

I am using PHP & I have a multi dimensional array which I need to search to see if the value of a "key" exists and if it does then get the value of the "field". Here's my array:

Array
(
    [0] => Array
    (
        [key] => 31
        [field] => CONSTRUCTN
        [value] => LFD_CONSTRUCTION_2
    )
    [1] => Array
    (
        [key] => 32
        [field] => COOLING
        value] => LFD_COOLING_1
    )
)

I want to be able to search the array for the "key" value of 31. If it exists, then I want to be able to extract the corresponding "field" value of "CONSTRUCTN".

I've tried using array_search(31, $myArray) but it does not work...

0

4 Answers 4

7

One-line solution using array_column and array_search functions:

$result = array_search(31, array_column($arr, 'key', 'field'));

print_r($result);   // CONSTRUCTN

Or with simple foreach loop:

$search_key = 31;
$result = "";
foreach ($arr as $item) {   // $arr is your initial array
    if ($item['key'] == $search_key) {
        $result = $item['field'];
        break;
    }
}

print_r($result);   // CONSTRUCTN
Sign up to request clarification or add additional context in comments.

Comments

6
function searchMultiArray($val, $array) {
  foreach ($array as $element) {
    if ($element['key'] == $val) {
      return $element['field'];
    }
  }
  return null;
}

And then:

searchMultiArray(31, $myArray);

Should return "CONSTRUCTN".

Comments

0

One liner solution:

$result = is_numeric($res = array_search(31, array_column($myArray, 'key'))) ? $myArray[$res]["field"] : "";

array_search accepts 2 parameters i.e the value to be search and the array, subsequently I've provided the array which needs searching using array_column which gets that particular column from the array to be searched and is_numeric is used to make sure that valid key is returned so that result can displayed accordingly.

2 Comments

This should work: $result = is_numeric($res = array_search(31, array_column($myArray, 'key'))) ? $myArray[$res]["field"] : "";
Because array_column() and array_search() both perform iterations on the input array, this approach is not likely to outperform a simple breakable foreach(). A foreach() will never do more than 1 loop over the input array and is capable of "short-circuiting". This answer possibly loops over the input 2 full times.
-1

I haven't tested, but I think this should do it.

function searchByKey($value, $Array){
    foreach ($Array as $innerArray) {
        if ($innerArray['key'] == $value) {
            return $innerArray['field'];
        }
    }
}

Then calling searchByKey(31, $myArray); should return 'CONSTRUCTN'.

1 Comment

And..... Looks like I should refresh the page before posting! @gmc already posted almost the exact same function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.