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.
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.
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.