PHP 5.3 Introduction to Anonymous Functions

Standard

New to PHP 5.3 is the introduction of anonymous function. Anonymous functions also known as closures are methods that do not require a specified name to be assign to a function.

Prior to 5.3

function firstName($name) {
   echo $name;
}
$this->test('Greg');

Now using anonymous function

$firstName = function($name) {
    echo $name;
};
$firstName('Greg');

As you can see we are accomplishing the same tasks, however the anonymous function method do become useful if you wish to write them for definitions of other methods.

Take for example that we want to filter out all values that do not equal 3 or 4.

$myDefinition = function ($v) {
            return ($v == 3 || $v == 4);
};
$values = array(23, 34, 4, 12, 6);
$output = array_values(array_filter($values, $myDefinition));

The result is as expected.

array(
	(int) 0 => (int) 4
)

Converting a json object to an array

Standard

Using restful web services relies on json results. You need your json object to be decoded and then converted to a array. Using the set library from CakePHP we can accomplish this. In this example I send a message to Android push gateway, then attempt to read the result.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: key= ENTER_YOUR_KEY',
    'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
   'registration_ids' => $registation_ids,
   'data' => array("m" => $message),
)));

$result = curl_exec($ch);
if ($result === FALSE) {
   // do error handling
   debug('curl request failed');
}

// The json decoding / converting line
$data = Set::reverse(json_decode($jsonresult));

The data variable now contains an array of information ready to parse.

Multisort by key

Standard

In some situations you want to organize your arrays numerically, or by a date that is in your array on a given value. This method takes in an array, attempts to sort it in the direction specified based on the field parameter (depth 1) designated. If the field you are passing in is a date, it can also formatted and arrange.

I used this particular method for organizing names based on a given rating, then by date of birth.

Usage:

$data = array(
            'Justin' => array('Points' => 5),
            'Thomas' => array('Points' => 1),
            'Adam' => array('Points' => 10)
        );

$result = $this->multiSort($data, “SORT_DESC”, “Points”, false);
print_r($result);

 

Note: additional depths can be specified by changing “Points” to “Points/Depth3Field” and so on…

Result:

array(
	'Adam' => array('Points' => 10),
	'Justin' => array('Points' => 5),
	'Thomas' => array('Points' => 1)
)

Method:

/**
 * Private multiSort
 *
 * @array() $data
 * @var $sortDirection
 * @var $field
 * @bool $isDate
 * @return $data (sorted)
 */
private function multiSort($data, $sortDirection, $field, $isDate) {
    if (empty($data) || !is_array($data) || count($data) < 2) {
        return $data;
    }

    $parts = explode("/", $field);
    foreach ($data as $key => $row) {
        $temp = &$row;
        foreach ($parts as $key2) {
            $temp = &$temp[$key2];
        }
        $orderByDate[$key] = ($isDate ? strtotime($temp) : $temp);
    }
    unset($temp);
    unset($parts);

    if ($sortDirection == "SORT_DESC") {
        array_multisort($orderByDate, SORT_DESC, $data);
    } else {
        array_multisort($orderByDate, SORT_ASC, $data);
    }
    unset($orderByDate);
    return $data;
}