Debug php code on browser

December 04, 2019

In javascript, you can console.log(‘whatever”) in your browser for troubleshooting. However, in php code, a little bit trick is required to do so. Here are the steps:

    function debug_to_console($data) {
        $output = $data;
        if (is_array($output))
            $output = implode(',', $output);

        echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
    }
  1. In the line that you need to console log, add this code

    debug_to_console(“Test”);

  2. If what you need to debug is an object, you can also log it via

    debug_to_console(json_encode($foo));

Open developer browser, and you should be able to see the console.log of the php object.


Profile picture

Experience in software development, application architecture, and deploying cloud solutions for enterprise customers. Strong hands-on skills with a Master's degree in Computer Science and business acumen with a master of business administration (MBA) in Finance. Certified in Amazon Web Services (AWS), Google Cloud Platform (GCP), Microsoft Azure, Kubernetes (CKA, CKAD, CKS, KCNA) and Scrum (PSM, PSPO) with experience in building banking products from scratch. Connect on Linkedin

© 2022, @victorleungtw