php get array value with default

Code snippet to get a value from php array and return a default value it key does not exist

function get_value($arr, $key, $default=null) {
  return array_key_exists($key, $arr) ? $arr[$key] : $default;
$arr1 = array('k1' => 'v1');
echo get_value($arr1, 'k1', 'NO_VAL') . "\n";
echo get_value($arr1, 'k2', 'NO_VAL') . "\n";

Output from above code

php code1.php 
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments