Skip to content

Instantly share code, notes, and snippets.

@bxt
Created February 26, 2011 14:42
Show Gist options
  • Save bxt/845259 to your computer and use it in GitHub Desktop.
Save bxt/845259 to your computer and use it in GitHub Desktop.
Prepare array with false-Values for undefinded keys with array_fill_keys (in PHP >= 5.3.0)
<?php
$in_array=array("foo"=>"fooval","baz"=>"bazval");
$in_array+=array_fill_keys(array("foo","bar","baz"),false);
// array_fill_keys is since PHP 5.2.0
// useage:
echo $in_array["foo"]?:"foodef";
// short ternary operator is since PHP 5.3.0
echo "\n";
echo $in_array["bar"]?:"bardef";
//now you don't have to write:
// echo isset($in_array["bar"])?$in_array["bar"]):"bardef";
echo "\n";
echo $in_array["baz"]?:"bazdef";
echo "\n";
/* Output:
fooval
bardef
bazval
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment