Tag Archives: Notation

Using PHP’s array_diff in Algorithm Development

array_diff can be really powerful. Once you’ve to find the different elements between two arrays you’ve to use array_diff. Here’s a case when you can use it while coding a simple algorithm.

The Task

You’ve one array with tickets of linked destinations – so you start from one city to another, than next and so on. Each element is an array with “from” and “to” destinations:

$inputTickets = array(
    0 => array('from' => 'barcelona', 'to' => 'madrid'),
    1 => array('from' => 'sofia', 'to' => 'paris'),
    2 => array('from' => 'madrid', 'to' => 'milano'),
    3 => array('from' => 'paris', 'to' => 'barcelona'),
    4 => array('from' => 'cupertino', 'to' => 'sofia'),
    5 => array('from' => 'milano', 'to' => 'valencia'),
    6 => array('from' => 'valencia', 'to' => 'nice'),
    7 => array('from' => 'mountain view', 'to' => 'cupertino'),
);

It’s easy to construct two arrays – the “from” destinations array and the “to” destinations array, and here the easiest way to get the starting point of the whole trip, because of the fact that these are linked tickets.

$fromDestinations = $toDestinations = array();
 
foreach ($inputTickets as $k => $v) {
    $fromDestinations[] = $v['from'];
    $toDestinations[]   = $v['to'];
}
 
// and finally get the starting point
$startPoint = array_diff($fromDestinations, $toDestinations);

Conclusion

Beside of knowing several algorithm techniques, there’s also need of knowing the language syntax and possibilities – in that case PHP’s