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);


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

One thought on “Using PHP’s array_diff in Algorithm Development

  1. Pingback:

Leave a Reply

Your email address will not be published. Required fields are marked *