Display debug and test information effectively in php
If you’ve worked in PHP, you know that debugging things in the middle of website code can be tedious. If you want to echo out a variable or boolean in a spot that isn’t visually accessible, then you will have a frustrating time viewing the source each page refresh.
A convenient way around this is to create a helper method that returns preformatted text. Ideally you want to define this in a global spot that you can call from anywhere (such as functions.php if you are using WordPress).
echo '<pre>'; print_r($input); echo '</pre>';
Then to call it in our code, we would reference with:
What this does is it uses php’s “print_r” method that dumps out any information in the variable in a preformatted block that is indented and sectioned off. This goes for strings, objects, arrays, etc. So if I had an array such as:
$my_arr = array('red', 'yellow', 'blue');
Echoing this out will only return “Array”. Now if you use the new “pk_print” method we created like so:
The result will be a much better, more informative piece of debug information.
It’s a small snippet, but it can save you a lot of time and repeat coding!