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

<?php
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 
v1
NO_VAL
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments