8

I have a question regarding ArrayObject. I wanted to use array_slice in an ArrayObject class and I couldn't. Is there a way to do it, without needing to write an "slice" method to the class that implements ArrayObject?

pocesar
  • 6,860
  • 6
  • 56
  • 88

2 Answers2

4

You can always work on the array copy:

$array = $object->getArrayCopy();
// modify $array as needed, e.g. array_slice(....) 
$object = new ArrayObject($array);

There sometime in the past was the idea to make all functions that accept arrays (or probably many of them) to accept ArrayObject as well. But I dunno how far that has gone and if it's still followed. I think ArrayObject is more a behavioural thing than actually replacing the native array in PHP.

Related question: PHP Array and ArrayObject

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • This is easy to implement, but it's bad on memory. If that's important, it will be worth it to just implement your own ArrayObject-like class where you have access to the private array data such that you can manipulate it directly. – Matthew Jul 08 '11 at 18:18
  • I must admit I have no clue about ArrayObject internals. – hakre Jul 08 '11 at 18:59
  • I was looking to avoid the use of getArrayCopy() because of the size of the array (+400k items). – pocesar Jul 08 '11 at 21:52
  • Just curious, is there a reason that blocks you from using just a standard array firsthand? And/or is extending ArrayObject an option for in your case? – hakre Jul 08 '11 at 21:54
  • it's a result from a database, the original class is an ArrayObject with some extra implementations (mostly iterators). extending this class is some messy business – pocesar Jul 10 '11 at 00:02
  • If you don't want to deal with the array copy or extending the object itself, you could do this vith a decorator or visitor. – hakre Jul 10 '11 at 10:16
  • JEEBUS FRACTURED CHROMOSOME. I've been programming in PHP for 15 years and I am STILL learning about further and further inconsistencies in the standard library APIs. – Szczepan Hołyszewski Jul 03 '21 at 14:26
  • Yes, we can have these moments. Maybe understand the subtle difference between SPL and the core library ^^ – hakre Jul 03 '21 at 14:48
0

Having a class that wraps php array functions is not that bad idea. Will make code much cleaner.

echo $myAry->slice(10, 5)->reverse()->join(", ");

Just like a normal language, you know.

user187291
  • 53,363
  • 19
  • 95
  • 127
  • that looks really cool @hakre. @stereofrog, how the data should be accessed inside the slice() method without duplicating data? – pocesar Jul 08 '11 at 21:53