I'd say you are building your array backwards.
Instead of this:
$contents['quantity'][$count] = $row->quantity;
$contents['title'][$count] = $row->title;
$contents['code'][$count] = $row->code;
$count++;
Do this:
$contents[$count]['quantity'] = $row->quantity;
$contents[$count]['title'] = $row->title;
$contents[$count]['code'] = $row->code;
$count++;
This will return you an array that you can traverse with a for loop easily. Also it's more logical to read $contents[row1][value of quantity], as apposed to $contents[value of quantity][for row 1].
As for getting your results, I've alwasy had trouble passing arrays, so I usually call them by referance.
function display_contents($table, $session, &$contents) {
// Code removed
return $count;
}
And when I use that function I do it this way:
$contents = array();
$count = display_contents($table, $session, $contents);
Then I have my array and I know how many values exists in it for my looping.