1

In PHP, how should I convert an SplDoublyLinkedList to an array? As far as I can see, there is no toArray method or suchlike.

Obviously I can implement this myself, but I expected that there would be an efficient provided method for this.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
jameshfisher
  • 34,029
  • 31
  • 121
  • 167

1 Answers1

2

You probably don't need to do this: SplDoublyLinkedList implements Iterator, ArrayAccess and Countable, meaning you can treat it like an array in almost all of your code.

If you need to persist it, it's safe to use in serialize. There should not be a need to actually transform it into an array unless you're calling a built-in function that operates only on real arrays.

If you absolutely must transform it into a real array, you can take advantage of foreach working with iterators:

$l = new SplDoublyLinkedList();
$l->push('a');
$l->push('b');
$l->push('c');
$l->unshift('d');
var_dump($l);
/*
class SplDoublyLinkedList#1 (2) {
  private $flags =>
  int(0)
  private $dllist =>
  array(4) {
    [0] =>
    string(1) "d"
    [1] =>
    string(1) "a"
    [2] =>
    string(1) "b"
    [3] =>
    string(1) "c"
  }
}
*/

$c = array();
foreach($l as $k => $v) { $c[$k] = $v; }
var_dump($c);
/*
array(4) {
  [0] =>
  string(1) "d"
  [1] =>
  string(1) "a"
  [2] =>
  string(1) "b"
  [3] =>
  string(1) "c"
}
*/

You may need to rewind the list before this.

Charles
  • 50,943
  • 13
  • 104
  • 142
  • Presumably `SplDoublyLinkedList` gives me O(n) array access? – jameshfisher Jan 30 '14 at 14:07
  • I'm not sure actually, but [normal array lookups seem to be O(log n)](http://stackoverflow.com/a/2484455/168868), if it actually matters to you. Note the graph. For most realistic array sizes, you aren't going to need to worry about performance. Don't engage in premature optimization, break out xdebug and profile the code to *prove* that it's array access that's slowing your code down. – Charles Jan 30 '14 at 17:48