Category Archives: Programming

Programming hints, tips, setups and tutorials

PHP: Figure out which Function called Your Function Programming 03 JUL 2016

When troubleshooting code, it is often quite handy to know what function called the function that you are busy working your way through. To do this you need a backtrace, and PHP makes getting one pretty easy thanks to its debug_backtrace function.

If you are interested in only the calling function name itself, then this neat little function should work quite nicely:

function GetCallingFunctionName($debug = false) {
//Returns the calling function through a backtrace
        $r = '';
        $debugString = '';
        $caller = debug_backtrace();
        if ($debug === true) {
            $debugString.= ' <p>START: debug_backtrace result:</p>';
            $debugString.= '<pre>';
            $debugString.= print_r($caller, true);
            $debugString.= '</pre>';
            $debugString.= '<p>END: debug_backtrace result:</p>';
        $caller = $caller[2];
        $r .= $caller['function'] . '()';
        if (isset($caller['class'])) {
            $r .= ' in ' . $caller['class'];
        if (isset($caller['object'])) {
            $r .= ' (' . get_class($caller['object']) . ')';
        return $r . $debugString;

Worth jotting down for the next time a function is giving me a headache for no apparent reason!

one-handed backhand tennis shot

Related Link: debug_backtrace | Source 1

Solved: F3 Framework Route is running Twice Programming 02 JUL 2016

I’ve inherited a project written using the Fat-Free Framework (or F3 Framework), which is billed as being a lightweight PHP micro-framework that is intended to be easy-to-use and fast, with a gentle learning curve thrown in for good measure. (In fairness, all three of these points seem to be holding relatively true thus far…)

fat-free framework php

Anyway, the project was written by an outsourced Polish developer, and now that he is no longer available, I’m bringing it in-house and expanding on it. Of course, this means that I’m refactoring it a little bit to better suit my own coding style. However, I hit an annoying snag which embarrassingly held me up for far longer than what it should have.

After making a class/controller name change, I was testing my routing when it became apparent that all of a sudden, one of my routes was running it’s function call twice.

An annoying issue to say the least.

So just a heads up, before you tear your hair out – be sure that your target function does in fact not share the same name of your newly renamed class in which said function resides.

If it does, then the framework will call the function through the run() routing as expected, and following that, the function will be called again… because as you might have noticed by now, the fact that your function is the same name as the class means that it is of course a constructor function.

So yes. I’ve jotted this down as a reminder to myself, that sometimes I’m an idiot.

Related Link: Fat-Free Framework

JavaScript: Check if an Object Property exists Programming 23 FEB 2016

A lot of warnings in code that I have to maintain often stem from the fact that the initial developer never bothers checking whether or not a given property of an object exists before trying to use it.

We’ve got a couple of options available to us to check whether or not a property actually exists in a given object, including the simple checking on whether or not the typeof returns ‘undefined’, or even using a basic in to check.

In practice (checking if property name exists in object user):

//Example of 'typeof' check - 
//Note: Of course, this could provide a false positive if the property value is actually set to 'undefined'
if (typeof === 'undefined') {
console.log('name property is missing');

//Example of 'in' check
if (!('name' in user)){
console.log('name property is missing');

A better, although slightly more costly (in terms of speed) check is to use the hasOwnProperty() method, which checks if the object on its own (not through one of its ancestors) has the given property or not.

In practice:

//Exammple of 'hasOwnProperty' check
if (!user.hasOwnProperty('name')) {
    console.log('name property is missing');

Of course, you probably should probably also check that the actual object itself exists first!

chimpanzee using a laptop to fix a problem

Solved: Image in div has a Thin Line Underneath Programming 11 JUN 2015

I noticed an annoying issue while working on some design elements on the survey element of my configurable feedback system Kinetica (for Touchwork) the other day. Essentially an image nestled inside a <div> element was rendering with an unsightly little line of space underneath it, breaking the visual effect that I wanted.

Perplexed (because the CSS inspector wasn’t showing anything untoward), I turned to Google and pretty soon had both the reason and the solution.

As it turns out, by default images are rendered as inline elements as opposed to block elements. In other words, it is rendered and treated like a letter/character, meaning that by default the line it is on has space below for the ‘descenders’ that you find on letters like y, j, p and q. This is then the line that you see below the image, because obviously it sits square on the line.

There are three possible fixes you can employ here. If you don’t want to do anything unnatural, you can get around the problem by simply specifying an appropriate vertical-align css style on the image, e.g. style=”vertical-align:bottom;”

Another fix that will work quite nicely is by specifying the line height of the parent container to 0 pixels, e.g. #div { line-height: 0;} <- of course, this assumes that you’re not going to have text anywhere in this parent container.

Finally, a just as effective trick would be to simply declare the image to be displayed as a block element, e.g. style=”display:block”

So with all that said and done, employing any of the tricks above will turn this:

thin line under image in div

into this:

thin line under image in div solved

Related Link: W3Schools

PHP: How to Convert a Date/Time from UTC to another Time Zone Programming 27 MAR 2015

Having previously shown you a useful way of quickly converting a timestamp into a formatted date string, here’s a quick way of actually getting a date/time in a time zone that you actually want – and again we turn to the powerfull PHP DateTime class to do this for us.

//here we'll use a UTC (time zone independent) time for our example
//(remember, time() always returns a UTC timestamp)
$dateTimeEnd = new DateTime('@' . time());
echo $dateTimeEnd->format('Y-m-d H:i:s');            
//now let's change to GMT+2 (SAST - South African Standard Time)
$dateTimeEnd->setTimezone(new DateTimeZone('Africa/Johannesburg'));
echo $dateTimeEnd->format('Y-m-d H:i:s');

As you can see, the setTimezone function of the DateTime class does all the heavy lifting for us, making it a snap to convert timestamps between different time zones.

Just a note, if you want to get the current time zone that your script is executing under, you can make use of date_default_timezone_get:

if (date_default_timezone_get()) {
    echo 'current time zone: ' . date_default_timezone_get() . '<br />';

A handy tip to remember then in other words!

world map showing time zones

Related Link:

PHP: How to Convert a Timestamp into a Date String Programming 26 MAR 2015

Unix timestamps aren’t exactly human readable representations of time. After all, a Unix timestamp is the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Usually one wants to show this to a user in a much friendlier date time format, like the tried and trusted Y-m-d H:i:s standard, e.g. ‘2015-03-23 09:00’.

It turns out achieving this formatted display is relatively easy: just use the standard DateTime class!

You can use a timestamp as construct parameter if you add the @-sign at the front. Once that is done, simply use the format function to return a user friendly date/time string:

$dateTimeEnd = new DateTime('@1427105451'); 
echo $dateTimeEnd->format('Y-m-d H:i:s'); //prints 2015-03-23 10:10:51

Quick and simple.


Related Link:

jQuery UI Autocomplete: How to clear the Search Text after Selection Programming 24 MAR 2015

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. One of the useful widgets in the collection is the Autocomplete widget, which enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

Easy to implement, works like a charm, the question then is how does one clear the search text after the user makes a selection from the autocomplete list?

Simply setting the value to ” in the select event function declaration won’t work out of the box, because the select event occurs before the field is actually updated – in other words, your change will be lost when the textbox is updated. To prevent this from happening, you essentially need to cancel the event to stop it from running to completion – in other words, return false.

So in practice, your declaration should look like this:

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
var availableTags = [
    $( "#tags" ).autocomplete({
      source: availableTags,
      select: function(event, ui) {
          this.value = "";
          return false;

And that is all there is to clearing the search term from the Autocomplete box after a user selects something!

pink convertible bug - volkswagen beetle

Related Link:

jQuery UI: How to Select All Text when the User clicks on the Autocomplete control Programming 20 MAR 2015

The jQuery UI toolbox gives you a lot of new controls to play around with if you are already using the awesome jQuery library, one of which it the very useful autocomplete control.

Essentially “Autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering. Any field that can receive input can be converted into an Autocomplete, namely, <input> elements, <textarea> elements, and elements with the contenteditable attribute.

By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.”

The problem arises when something is pre-populated in the autocomplete element, i.e. something had previously been selected. When you click on the control to start searching, your newly entered text simply appends on to the end of the existing text, resulting in a gobbledygook search!

To combat this we essentially need to select all text when the autocomplete box is called upon, and it turns out to do this we need to work with the mouse up event.

In practice, the code to achieve this select all text on entering the autocomplete search box looks like this:

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
$(document).ready(function() {
    var availableTags = [
    $( "#tags" ).autocomplete({
      source: availableTags
    }).on('mouseup', function() {

As you can see, we add the mouseup event monitor at input initialization, and with this now in place, every time the user clicks on the control any existing text is automatically selected – meaning that as soon as the user starts entering text, whatever was there previously will now be lost. Victory!

laptop click with mouse

Related Link:

jQuery: How to Break Out of an Each Loop Programming 16 MAR 2015

The ever so useful jQuery javascript library has a homegrown loop function entitled .each(), which allows you to iterate over a jQuery object, and at the same time execute a function for each matched element.

Very useful indeed.

However, sometimes you might need to break out of a loop early (for example, maybe your loop has the potential of carrying on forever – which obviously is not so great for your patiently waiting audience) – and this is how you do it:

To break a $.each() loop, you have to return false in the loop callback function. (Returning true is equivalent to continue in a normal loop, in other words it skips to the next iteration – exactly the opposite of what you are trying to achieve!)

An example:

$('.lotsOfTheseClassesExist').each(function(i, item){
return false; //exits the loop

So your break statement for a jQuery each() loop is literally return false.

girl in pink high heels and a black leotard with lots and lots of shiny hula hoops

jquery logo

Related Link: