Category Archives: PHP



Convert php array to UTF8 recursively

This simple php function converts recursively all values of an array to UTF8.
The function mb_detect_encoding (line 4) checks if the value already is in UTF8, this way it will not reconvert.

1
2
3
4
5
6
7
8
9
10
function utf8_converter($array)
{
    array_walk_recursive($array, function(&$item, $key){
        if(!mb_detect_encoding($item, 'utf-8', true)){
                $item = utf8_encode($item);
        }
    });
 
    return $array;
}

Anonymous functions (closures) in PHP >= 5.3

According to the PHP documentation, anonymous functions, or closures, allow the creation of functions that haven’t got a specified name.

Simple example:

$greeting = function($name)
{
    printf("Hello %s\r\n", $name);
};
 
$greeting('World');

But in this example we’ll go a little further.
Imagine you have this array:

$users = array(
             array('id' => 1, 'name' => 'Steve', 'birthday' => '1984-02-17'),
             array('id' => 2, 'name' => 'Bill', 'birthday' => '1985-07-07'),
             array('id' => 3, 'name' => 'James', 'birthday' => '1974-11-17')
         );

If we want to get the ids for each user, we would do something like this:

$ids = array();
foreach ($users as $user) {
    $ids[] = $user['id'];
}

But there is a much more elegant way to do this using anonymous functions (closures):

$ids = array_map(function ($user) {
    return $user['id'];
}, $users);

Much cleaner and elegant… Now we want to get the users who were born after 1980. Normally do this:

$filtered_users = array();
$start_date = strtotime('1980-01-01');
foreach ($users as $user) {
    if (strtotime($user['birthday']) >= $start_date) {
        $filtered_users[] = $user;
    }
}

Now we will use again anonymous functions or closures:

$start_date = strtotime('1980-01-01');
$filtered_users = array_filter($users, function($user) {
    global $start_date;
    return strtotime($user['birthday']) >= $start_date;
});

These are just a few examples of anonymous functions or closures in PHP.

How to get GPS coordinates from an address with PHP and Google Maps

With this simple method in PHP we can get the GPS coordinates from an address using Google Maps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
 
function getCoordinates($address){
    $address = urlencode($address);
    $url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=" . $address;
    $response = file_get_contents($url);
    $json = json_decode($response,true);
 
    $lat = $json['results'][0]['geometry']['location']['lat'];
    $lng = $json['results'][0]['geometry']['location']['lng'];
 
    return array($lat, $lng);
}
 
 
$coords = getCoordinates("Wall Street, New York");
print_r($coords);
 
 
/*
Prints:
 
Array
(
    [0] => 41.3936254
    [1] => 2.1634189
)
*/