いずれ役に立ちそうな PHPからJavaScriptに変数を渡すまとめ

http://qiita.com/cither/items/b98cc4e237dcc8f7e51f

<?php
    $array = array("hoge" => "fuga");
?>
<script>
    var array = <?php echo json_encode($array, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
    console.log(array); // Object { hoge: "fuga" }
</script>
function json_safe_encode($data){
    return json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
}
<?php
    $null        = null;
    $string      = "hoge";
    $emptyString = "";
    $array       = array("hoge", "fuga");
    $empty_array = array();
    $asoc_array  = array("hoge" => 1, "fuga" => 2);
    $boolean     = false;
    $str_boolean = "false";
    $zero        = 0;
    $str_zero    = "0";
    $float       = 0.12;
?>
<script id="script" src="script.js"
    data-null         ='<?php echo json_safe_encode($null); ?>'
    data-string       ='<?php echo json_safe_encode($string); ?>'
    data-empty-string ='<?php echo json_safe_encode($empty_string); ?>'
    data-array        ='<?php echo json_safe_encode($array); ?>'
    data-empty-array  ='<?php echo json_safe_encode($empty_array); ?>'
    data-asoc-array   ='<?php echo json_safe_encode($asoc_array); ?>'
    data-boolean      ='<?php echo json_safe_encode($boolean); ?>'
    data-str-boolean  ='<?php echo json_safe_encode($str_boolean); ?>'
    data-zero         ='<?php echo json_safe_encode($zero); ?>'
    data-str-zero     ='<?php echo json_safe_encode($str_zero); ?>'
    data-float        ='<?php echo json_safe_encode($float); ?>'
></script>
var $script     = $('#script');
var _null       = JSON.parse($script.attr('data-null'));
var string      = JSON.parse($script.attr('data-string'));
var emptyString = JSON.parse($script.attr('data-empty-string'));
var array       = JSON.parse($script.attr('data-array'));
var emptyArray  = JSON.parse($script.attr('data-empty-array'));
var asocArray   = JSON.parse($script.attr('data-asoc-array'));
var boolean     = JSON.parse($script.attr('data-boolean'));
var strBoolean  = JSON.parse($script.attr('data-str-boolean'));
var zero        = JSON.parse($script.attr('data-zero'));
var strZero     = JSON.parse($script.attr('data-str-zero'));
var float       = JSON.parse($script.attr('data-float'));


console.log(_null);       // null
console.log(string);      // "hoge"
console.log(emptyString); // ""
console.log(array);       // Array [ "hoge", "fuga" ]
console.log(emptyArray);  // Array [  ]
console.log(asocArray);   // Object { hoge: 1, fuga: 2 }
console.log(boolean);     // false
console.log(strBoolean);  // "false"
console.log(zero);        // 0
console.log(strZero);     // "0"
console.log(float);       // 0.12