There is a getValue () function that takes an array of keys and values ​​from the getArray () function and returns value for key = $ foo (if any).

function getArray() { // Возвращается массив типа: // Array ( // [0] => Array ( [key] => a [value] => а ) // [1] => Array ( [key] => b [value] => б ) // [2] => Array ( [key] => c [value] => в ) // ) } function getValue( $foo ) { $arr = array(); foreach(getArray() as $i) { $arr[$i['key']] = $i['value']; } if ( isset( $arr[$foo] ) ) return $arr[$foo]; else return 'Nope'; } 

This code works, but visually I never like it. Is there a way to simplify or improve the getValue function?

While I found only this solution:

 function getValue( $foo ) { foreach(getArray() as $i) { if ($i['key'] == $foo) return $i['value']; } return 'Nope'; } 
  • And what is not satisfied with the second option? It is the best solution. Passing through the array is done exactly to the desired element. - KiTE
  • I wonder what other options there are. - Denis Khvorostin

1 answer 1

 function getValue($foo){ if(array_key_exist($foo, $arr)){ return $arr[$foo] }else{ return null; } } 
  • one
    Exactly and you need to return null in case of failure. Only the second parameter in array_key_exist is needed, where to look for something :) - pavelbel
  • The input array is multidimensional. array_key_exist () takes two parameters. Well, as a replacement for the if (isset ($ arr [$ foo])) return $ arr [$ foo]; else return 'Nope'; - Denis Khvorostin
  • @Khvorostin, why not replace <pre> <code> // Returns an array of the type: // Array (// [0] => Array ([key] => a [value] => a) // [1] = > Array ([key] => b [value] => b) // [2] => Array ([key] => c [value] => c) //) </ code> </ pre> on <pre> <code> // Returns an array of the type: // Array (// [0] => Array ('a' => 'a') // [1] => Array ('b' => 'b ') // [2] => Array (' c '=>' in ') //) </ code> </ pre>? - stck
  • @stck Because it is data from a DB. If there is a query query to the database, when a non-multidimensional array is returned, but a simple one, this would strongly ask me for the task. - Denis Khvorostin
  • @Khvorostin, there are always options. But for this you need to look at the getValue () method - stck