Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print or Display PHP array in Browser Console or in Javascript

i need to print php array in browser console using javascript

here i shared my code

<?php
function browser_console($data) {
    echo "<script>console.log('" . $data . "');</script>";
}

if anybody knows best code let me know .

thank you

like image 537
Kavin D Avatar asked Feb 19 '17 07:02

Kavin D


People also ask

Can you print to console in PHP?

The echo command is used in PHP to print any value to the HTML document. Use <script> tag inside echo command to print to the console.

Can I use PHP array in JavaScript?

You can easily use PHP array in javascript you only need to convert PHP array into JSON format Using json_encode() function. PHP array can be converted to JavScript array and accessible in JavaScript. Whatever the array type is, a single or multidimensional or indexed or associative array.

How do I view an array in PHP?

To display array structure and values in PHP, we can use two functions. We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array.

Which function is used to print an array in PHP?

Using print_r() function The most common method to print the contents of an array is using the print_r() function, which displays the human information about a variable. For an array, the values are displayed in a format that shows keys and elements.


2 Answers

I'm using

echo "<script>console.log(".json_encode(var_export($object, true)).");</script>";

as it allows you to display complex PHP objects and not only up to arrays.

like image 142
Patrick Avatar answered Nov 09 '22 12:11

Patrick


Try using json_encode()

Example

echo "<script>console.log('" . json_encode($data) . "');</script>";
like image 24
Abdullah Mallik Avatar answered Nov 09 '22 12:11

Abdullah Mallik