convert php associative array into javascript object

I looked a lot for an elegant solution to fix this issue without doing changing things over javascript or just replace quotes via preg_replace (for the case that the values would contain quotes) and end up doing it by myself. even if it's too late, I hope it would help those who are looking for the same solution.

function json_encode_advanced(array $arr, $sequential_keys = false, $quotes = false, $beautiful_json = false) {

    $output = "{";
    $count = 0;
    foreach ($arr as $key => $value) {

        if ( isAssoc($arr) || (!isAssoc($arr) && $sequential_keys == true ) ) {
            $output .= ($quotes ? '"' : '') . $key . ($quotes ? '"' : '') . ' : ';
        }

        if (is_array($value)) {
            $output .= json_encode_advanced($value, $sequential_keys, $quotes, $beautiful_json);
        } else if (is_bool($value)) {
            $output .= ($value ? 'true' : 'false');
        } else if (is_numeric($value)) {
            $output .= $value;
        } else {
            $output .= ($quotes || $beautiful_json ? '"' : '') . $value . ($quotes || $beautiful_json ? '"' : '');
        }

        if (++$count < count($arr)) {
            $output .= ', ';
        }
    }

    $output .= "}";

    return $output;
}

function isAssoc(array $arr) {
    if (array() === $arr) return false;
    return array_keys($arr) !== range(0, count($arr) - 1);
}

usage:

$array = [
    'someField' => '"value"', // double quotes for string if needed
    'labelField' => '"label"', // double quotes for string if needed
    'boolean' => false,
    'numeric' => 5,
    'render' => [
        'option' => 'function() {
            console.log("Hello World!");
            console.log(\'Hello World!\');
        }',
    ],
];
echo json_encode_advanced($array);

result:

{
    someField : "value",
    labelField : "label",
    boolean : false,
    numeric : 5,
    render : {
        option : function() {
            console.log("Hello World!");
            console.log('Hello World!');
        }
    }
}

The answer of Rohan Kumar is excellent except it uses jQuery to show the results.

This can be quicker and easier:

var words = <?php echo json_encode( $wordsArray ) ?>;
console.dir(words);

This gives you a one line result like Object ▶. Clicking on the will open the object and shows its contents.


You can use json_encode() to make array as an json object like,

var words = <?php echo json_encode($wordsArray) ?>;// don't use quotes
$.each(words, function(key, value) {
    console.log('stuff : ' + key + ", " + value);
});